实验4 函数与异常处理应用编程
1 #task1.py 2 print(sum) 3 sum = 42 4 print(sum) 5 def inc(n): 6 sum = n+1 7 print(sum) 8 return sum 9 sum = inc(7) + inc(7) 10 print(sum)
1.Built-in
2.Global
3.Local
4.Global
1 #task2_2.py 2 list1 = [1, 9, 8, 4] 3 print( sorted(list1) ) 4 print( sorted(list1, reverse=True) ) 5 print( sorted(list1, True) )
python内置函数sorted()中,参数reverse的传递方式必须使用关键字传递
1 #task2_3.py 2 def func(a, b, c, /, *, d, e, f): 3 return( [a,b,c,d,e,f] ) 4 print(func(1,2,3,d=4,e=5,f=6))
1 #task3.py 2 def solve(a, b, c): 3 ''' 4 求解一元二次方程, 返回方程的两个根 5 :para: a,b,c: int 方程系数 6 :return: tuple 7 ''' 8 delta = b*b - 4*a*c 9 delta_sqrt = abs(delta)**0.5 10 p1 = -b/2/a; 11 p2 = delta_sqrt/2/a 12 if delta>=0: 13 root1 = p1 + p2 14 root2 = p1 - p2 15 else: 16 root1 = complex(p1, p2) 17 root2 = complex(p1, -p2) 18 return root1, root2 19 20 21 while True: 22 try: 23 a,b,c = eval(input('Enter eqution coefficient: ')) 24 if a == 0: 25 raise 26 except: 27 print('invalid input, or, a is zero') 28 break 29 else: 30 root1, root2 = solve(a, b, c) 31 print(f'root1 = {root1:.2f}, root2 = {root2:.2f}') 32 print()
加一行代码会把说明信息打印出来
1 #task4.py 2 def list_generator(a,b,step=1): 3 list=[] 4 while a<=b: 5 list.append(a) 6 a+=step 7 return list 8 list1 = list_generator(-5, 5) 9 print(list1) 10 list2 = list_generator(-5, 5, 2) 11 print(list2) 12 list3 = list_generator(1, 5, 0.5) 13 print(list3)
1 #task5.py 2 def is_prime(n): 3 for i in range(2,int(n**0.5)+1): 4 if n%i==0: 5 return False 6 else: 7 return True 8 for j in range(2,21,2): 9 for k in range(2,j): 10 if is_prime(j-k): 11 print(f'{j}={k}+{j-k}') 12 break
1 #task6.py 2 def encoder(text:str): 3 ans=[] 4 for n in text: 5 x=ord(n) 6 if 65<=x<=90: 7 ans.append(chr((x-60)%26+65)) 8 elif 97<=x<=122: 9 ans.append(chr((x-92)%26+97)) 10 else: 11 ans.append(n) 12 return ''.join(ans) 13 14 def decoder(text1): 15 ans1=[] 16 for n in text1: 17 x1=ord(n) 18 if 65 <= x1 <= 90: 19 ans1.append(chr((x1 - 44) % 26 + 65)) 20 elif 97 <= x1 <= 122: 21 ans1.append(chr((x1 - 76) % 26 + 97)) 22 else: 23 ans1.append(n) 24 return ''.join(ans1) 25 26 27 28 text=input('输入英文文本:') 29 text1=encoder(text) 30 print(f'编码后的文本:{text1}') 31 print(f'解码后的文本:{decoder(text1)}')
1 #task7.py 2 def collatz(n): 3 if n%2==0: 4 return n/2 5 else: 6 return 3*n+1 7 try: 8 n=eval(input('Enter a positive integer:')) 9 if type(n)!=int or n<=0: 10 raise ValueError and NameError 11 except ValueError and NameError: 12 print('Error: must be a positive integer') 13 else: 14 list=[n] 15 while n!=1: 16 n=collatz(n) 17 list.append(n) 18 print(list)