实验四

task1
1
print(sum) 2 sum=42 3 print(sum) 4 5 def inc(n): 6 sum=n+1 7 print(sum) 8 return sum 9 sum=inc(7)+inc(7) 10 print(sum)

 

不是1.内置作用域2.全局作用域3.局部作用域4.全局作用域

task2_2

1 list1=[1,9,8,4]
2 
3 print(sorted(list1))
4 print(sorted(list1,reverse=True))
5 print(sorted(list1,True))

 

 

必须使用关键词传递

task2_3

1 def func(a,b,c,/,*,d,e,f):
2     return([a,b,c,d,e,f])
3 
4 print(func(1,2,3,d=4,e=5,f=6))

 

 task3

 1 def solve(a,b,c):
 2     '''
 3     求解一元二次方程, 返回方程的两个根
 4     :para: a,b,c: int 方程系数
 5     :return: tuple
 6     '''
 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 print(solve.__doc__)
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()

 

 task4

 1 def list_generator(a,b,c=1):
 2     d=[]
 3     while a<=b:
 4         d.append(a)
 5         a+=c
 6     return d
 7     
 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)

 

 task5

 1 def is_prime(n):
 2     i=2
 3     while i<n and n%i!=0:
 4         i+=1
 5     if i==n:
 6         return True
 7     else:
 8         return False
 9 for m in range(4,21,2):
10     for n in range(2,m):
11         if is_prime(n) and is_prime(m-n):
12             print(f'{m}={n}+{m-n}')
13             break
14         

 

 task6

 1 def encoder(text):
 2     a=[]
 3     for i in text:
 4         if 97<=ord(i.lower())<=117:
 5             i=chr(ord(i)+5)
 6         elif 118<=ord(i.lower())<=122:
 7             i=chr(ord(i)-21)
 8         a.append(i)
 9     return ''.join(a)
10 def decoder(text):
11     a=[]
12     for i in text:
13         if 102<=ord(i.lower())<=122:
14             i=chr(ord(i)-5)
15         elif 97<=ord(i.lower())<=101:
16             i=chr(ord(i)+21)
17         a.append(i)
18     return ''.join(a)
19 
20 a=input('输入英文文本:')
21 print(f'编码后的文本:{encoder(a)}\n对编码后的文本解码:{decoder(encoder(a))}')

 

 task7

 1 def collatz(n):
 2     if n%2:
 3         n=3*n+1
 4     else:
 5         n=int(n/2)
 6     return n
 7 
 8 n=input('Enter a positive integer:')
 9 try:
10     n=int(n)
11     if n<=0:
12         raise
13 except:
14     print('Error: must be a positive integer')
15 else:
16     a=[n]
17     while n!=1:
18         n=collatz(n)
19         a.append(n)
20     print(a)

 

posted on 2022-05-04 20:12  VolcanX  阅读(21)  评论(3编辑  收藏  举报