任务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
2.1
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,e=55,f=33)) print(func3(111,999,222,0,555,333)) print(func3(111,999,222,d=0,e=555,f=333))
2.2
list1=[1,9,8,4] print(sorted(list1)) print(sorted(list1,reverse=True)) print(sorted(list1,True))
2.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))
任务3
def solve(a,b,c): ''' :para:a,b,c:float :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 while True: try: t=input('输入一元二次方程系数a,b,c,或者,输入#结束:') if t=='#': print('结束计算,退出') break a,b,c=map(float,t.split()) if a==0: raise ValueError('a=0,不是一元二次方程') except ValueError as e: print(repr(e)) print() except: print('有其他错误发生\n') else: root1,root2=solve(a,b,c) print(f'root1={root1:.2f},root2={root2:.2f}') print()
任务4
# list_generator()函数定义 def list_generator(start, stop, step=1): result = [] i = start while i <= stop: result.append(i) i += step return result 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(x): for i in range(2,int(x**0.5+2)): a=x%i if a==0: break if a==0 and x!=2: return False elif a!=0 or x==2: return True for i in range(4,21,2): for x in range(2,i): y = i - x if is_prime(x) and is_prime(y): print(f'{i}={x}+{y}') break
任务6
def encoder(text): x1 = '' for i in text: if 'a' <= i <= 'z': i = chr((ord(i)-97+5) % 26 + 97) x1 += i elif 'A' <= i <= 'Z': i = chr((ord(i)-65+5) % 26 + 65) x1 += i else:x1 += i return x1 def decoder(text): x2 = '' for i in text: if 'a' <= i <= 'z': i = chr((ord(i)-97-5) % 26 + 97) x2 += i elif 'A' <= i <= 'Z': i = chr((ord(i)-65-5) % 26 + 65) x2 += i else: x2 += i return x2 text = input('输入英文文本: ') encoded_text = encoder(text) print('编码后的文本: ', encoded_text) decoded_text = decoder(encoded_text) print('对编码后的文本解码: ', decoded_text)
任务7
def collatz(n): lst = [] lst.append(n) while n != 1: if n %2 == 0: n = n/2 lst.append(int(n)) else: n = n*3 +1 lst.append(int(n)) return lst try: n = int(input('Enter a positive integer:')) if n <= 0: raise ValueError except ValueError: print('Error: must be a positive integer') else: print(collatz(n))
任务8
def func(a): if a==0: return 0 else: return 2*func(a-1)+1 while True: x=input() if x=='#': print('计算结束') break n=int(x) ans=func(n) print(f'n={n},ans={ans}')
标签:return,sum,实验,print,root1,def,root2 From: https://www.cnblogs.com/chaomifeng/p/17408078.html