实验四
测试1
print(sum) sum = 42 print(sum) def inc(n): sum = n+1 print(sum) return sum sum = inc(7) + inc(7) print(sum)
第一个 内置作用域
第二个 全局作用域
第三个 局部作用域
第四个 全局作用域
测试2
def func1(a, b, c, d, e, f): return [a,b,c,d,e,f] def func2(a, b, c,*, d, e, f): return [a,b,c,d,e,f] def func3(a, b, c, /, d, e, f): return [a,b,c,d,e,f] print( func1(1,9,2,0,5,3) ) print( func1(a=1, b=9, c=2, d=0, e=5, f=3) ) print( func1(1,9,2, f=3, d=0, e=5)) print( func2(11, 99, 22, d=0, e=55, f=33) ) print( func2(a=11, b=99, c=22, d=0,f=33,e=55) ) print( func3(111, 999, 222, 0, 555, 333)) print( func3(111, 999, 222, d=0, e=555, f=333) ) list1 = [1, 9, 8, 4] print( sorted(list1) ) print( sorted(list1, reverse=True) ) print( sorted(list1, True) )
python内置函数sorted()中,参数reverse的传递方式是否必须使用关键字传递?
是
测试三
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()
实验四
def list_generator(a,b,c=1): if c>=1: list1=[i for i in range(a,b+1)] list1=list1[::c] return list1 else: list2=[j for j in range(a,b+1)] list3=[] for s in range(a,b): list3.append(s+c) list2=list2+list3 list2=sorted(list2) return list2 list1 = list_generator(-5, 5) print(list1) list2 = list_generator(-5, 5, 2) print(list2) list3 = list_generator(1, 5, 0.5) print(list3)
测试五
def is_prime(n): if n <= 1: return False for i in range(2,(int(n**0.5)+1)): if n%i == 0: return False return True for i in range(4,21,2): for j in range(2,i): t=i-j if is_prime(t) and is_prime(j) and j<=t and j!=t: print(j,'+',t,'=',i)
测试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): list = [n] while list[-1]!= 1: if list[-1] % 2==0: list.append(int(list[-1]/2)) else: list.append(int(list[-1]*3+1)) return list try: n = eval(input('输入一个整数')) print(collatz(n)) except: print('must be a positive integer')