实验4
作者:互联网
#task1 print(sum) sum = 42 print(sum) def inc(n): sum = n+1 print(sum) return sum sum = inc(7) + inc(7) print(sum)
不是同一个变量名
line1:内置函数名
line3:赋值名
line7:局部变量
line11:全局变量
#task2—1 (代码框架) def func1(a, b, c, d, e, f): ''' 返回参数a,b,c,d,e,f构成的列表 默认,参数按位置传递; 也支持关键字传递 ''' return [a,b,c,d,e,f] def func2(a, b, c,*, d, e, f): ''' 返回参数a,b,c,d,e,f构成的列表 *后面的参数只能按关键字传递 ''' return [a,b,c,d,e,f] def func3(a, b, c, /, d, e, f): ''' 返回参数a,b,c,d,e,f构成的列表 /前面的参数只能按位置传递 ''' return [a,b,c,d,e,f] # func1调用:按位置传递、按参数传递都可以 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)) # func2调用:d,e,f必须按关键字传递 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) ) # func3调用:a,b,c必须按位置传递 print( func3(111, 999, 222, 0, 555, 333)) print( func3(111, 999, 222, d=0, e=555, f=333) )
实验任务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()
def list_generator(a,b,c=1): t=list() if c==int(c): for i in range(a,b+1,c): t.append(i) return(t) else: if 0<c<1: for i in range(a,b+1): t.append(i+c) return(t) else: for i in range(a,b+1,int(c)): t.append(i+c-int(c)) return(t) list1=list_generator(-5,5) print(list1) list1=list_generator(-5,5,2) print(list1) list1=list_generator(1,5,0.5) print(list1)
def is_prime(n): i=2 while(i<=n): if n%i!=0: i=i+1 else: if i==n: return True else: return False for i in range(2,21,2): for j in range(2,i): if is_prime(i-j) and is_prime(j): print(f'{i}={j}+{i-j}') break
def encoder(text:str): ans=[] for n in text: x=ord(n) if 65<=x<=90: ans.append(chr((x-60)%26+65)) elif 97<=x<=122: ans.append(chr((x-92)%26+97)) else: ans.append(n) return ''.join(ans) def decoder(text1): ans1=[] for n in text1: x1=ord(n) if 65 <= x1 <= 90: ans1.append(chr((x1 - 44) % 26 + 65)) elif 97 <= x1 <= 122: ans1.append(chr((x1 - 76) % 26 + 97)) else: ans1.append(n) return ''.join(ans1) text=input('输入英文文本:') text1=encoder(text) print(f'编码后的文本:{text1}') print(f'解码后的文本:{decoder(text1)}')
def collatz(n): if n%2==0: return n/2 else: return 3*n+1 try: n=eval(input('Enter a positive integer:')) if type(n)!=int or n<=0: raise ValueError and NameError except ValueError and NameError: print('Error: must be a positive integer') else: list=[n] while n!=1: n=collatz(n) list.append(n) print(list)
标签:return,sum,实验,print,root1,def,root2 来源: https://www.cnblogs.com/wwfzjhlsjhst/p/16257467.html