零基礎學程式設計021:獲取股票實時行情資料
阿新 • • 發佈:2022-05-03
task1
print(sum) sum = 42 print(sum) def inc(n): sum = n+1 print(sum) return sum sum = inc(7) + inc(7) print(sum)
第一個sum,內建作用域.第二個sum變數名,第三個sum區域性作用域,第四個sum全域性作用域
task2.2
list1 = [1, 9, 8, 4] print( sorted(list1) ) print( sorted(list1, reverse=True) ) print( sorted(list1, True) )
對比結果可知,sorted中,reverse的傳遞方式使用關鍵字傳遞
task2.3
def func(a, b, c, /, *, d, e, f): return( [a,b,c,d,e,f] ) print(func(1,2,3,d=4,e=5,f=6))
task3
def solve(a, b, c): ''' 求解一元二次方程, 返回方程的兩個根 :para: a,b,c: int 方程係數 :return: tuple ''' delta = b*b - 4*a*c delta_sqrt = abs(delta)**0.5 p1 = -b/2/a; p2= delta_sqrt/2/a if delta>=0: root1 = p1 + p2 root2 = p1 - p2 else: root1 = complex(p1, p2) root2 = complex(p1, -p2) return root1, root2 print(solve.__doc__) while True: try: a,b,c = eval(input('Enter eqution coefficient: '))if a == 0: raise except: print('invalid input, or, a is zero') break else: root1, root2 = solve(a, b, c) print(f'root1 = {root1:.2f}, root2 = {root2:.2f}') print()
task4
def list_generator(b,e,s=1): l=[] while b<e: l.append(b+s) b=b+s return l list1 = list_generator(-5, 5) print(list1) list2 = list_generator(-5, 5, 2) print(list2) list3 = list_generator(1, 5, 0.5) print(list3)
task5
def is_prime(n): if n==1: return False for i in range(2,n-1): if n%i==0: return False break else: return True l1=[] for i in range(2,21): if is_prime(i): l1.append(i) l2=[] for i in range(4,21): if i%2==0: l2.append(i) for i in l2: for j in l1: if (i-j)in l1: print(f'{i}={j}+{i-j}') break
task6
if __name__ == '__main__': main() import string s=input('輸入英文文字:') low=string.ascii_lowercase+'abcde' upp=low.upper() l=low+upp def encoder(s): for i in s: if i.isalpha(): s=s.replace(i,l[l.find(i)+5]) return s s2=encoder(s) l2=l[::-1] def decoder(s2): for i in s2: if i.isalpha(): s2=s2.replace(i,l2[l2.find(i)+5]) return s2 print(f'編碼後的文字:{encoder(s)}') print(f'對編碼後的文字解碼:{decoder(s2)}')
task7
def collatz(n): if n%2==0: n=n/2 return n else: n=3*n+1 return n l=[] try: n=eval(input()) if n<0 or type(n)!=int: raise except: print('Error:must be a positive integer') else: l.append(n) while n!=1: n=int(collatz(n)) l.append(n) print(l)