实验4
试验任务1:
print(sum) sum = 42 print(sum) def inc(n): sum = n+1 print(sum) return sum sum = inc(7) + inc(7) print(sum)
这4处使用的标识符sum是代表一个变量名吗?如果不是,请分别指出这4行中变量sum的作用域。
不是。1.内置作用域2.全局作用域3.局部作用域4.全局作用域
实验任务2:
list1=[1,9,8,4] print(sorted(list1)) print(sorted(list1, reverse=True)) print(sorted(list1, True))
python内置函数sorted()中,参数reverse的传递方式是否必须使用关键字传递?
需要。
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))
实验任务3:
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()
实验任务4:
def list_generator(a,b,step=1): list=[] i=a while a<=i<=b: list.append(i) i+=step return list list1 = list_generator(-5, 5) print(list1) list2 = list_generator(-5, 5, 2) print(list2) list3 = list_generator(1, 5, 0.5) print(list3)
实验任务5:
def is_prime(num): if num>1: for i in range(2,num//2+1): if num%i==0: return False break else: return True else: return False for a in range(0,21): if a%2==0: for i in range(2,a): if is_prime(a-i): print(f'{a}={i}+{a-i}') break
实验任务6:
def encoder(n): list=[] for i in n: i = ord(i) if 97 <= i <= 117 or 65 <= i <= 85: i = i + 5 elif 117 < i <= 122 or 85 < i <= 90: i = i - 21 else: i = i list.append(chr(i)) return ''.join(list) def decoder(n): n=encoder(n) list=[] for i in n: i=ord(i) if 102 <= i <= 122 or 70 <= i <= 90: i=i-5 elif 97 <= i < 102 or 65 <= i < 70: i=i+21 else: i=i list.append(chr(i)) return ''.join(list) n = input('输入英文文本:') print('编码后' + encoder(n)) print('编码后' + decoder(n))
实验任务7:
def collatz(n): if n%2==0: return n/2 else: return 3*n+1 try: a=eval(input('Enter a positive integer:')) if int(a)!=a or a<=0: raise ValueError and NameError except ValueError and NameError: print('Error: must be a positive integer') else: list=[a] while a!=1: a=collatz(a) list.append(a) print(list)