1 print(sum) 2 sum = 42 3 print(sum) 4 def inc(n): 5 sum = n+1 6 print(sum) 7 return sum 8 sum = inc(7) + inc(7) 9 print(sum)
1.Built-in
2.Global
3.Local
4.Global
1 def func(a, b, c, /, *, d, e, f): 2 return ([a, b, c, d, e, f]) 3 4 5 print(func(1, 2, 3, d=4, e=5, f=6))
1 def solve(a, b, c): 2 ''' 3 求解一元二次方程, 返回方程的两个根 4 :para: a,b,c: int 方程系数 5 :return: tuple 6 ''' 7 delta = b*b - 4*a*c 8 delta_sqrt = abs(delta)**0.5 9 p1 = -b/2/a; 10 p2 = delta_sqrt/2/a 11 if delta>=0: 12 root1 = p1 + p2 13 root2 = p1 - p2 14 else: 15 root1 = complex(p1, p2) 16 root2 = complex(p1, -p2) 17 return root1, root2 18 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()
1 def list_generator(begin, end, step=1): 2 ls = [] 3 a = begin
1 def is_prime(n): 2 if n < 2: 3 return False 4 for i in range(2,int(n**0.5)+1): 5 if n % i == 0: 6 return False 7 return True 8 9 h=[i for i in range(21)] 10 for x in h[::2]: 11 for a in range(0,21): 12 if is_prime(a) is True: 13 if is_prime(x-a) is True: 14 print(f'{x}={a}+{x-a}') 15 break 16 else: 17 a+=1 18 else: 19 a+=1
1 def encoder(a): 2 """对文本加密""" 3 result = '' 4 for i in range(len(a)): 5 if ord(a[i]) in range(65, 91): 6 result+=chr((ord(a[i])-65+5)%26+65) 7 elif ord(a[i]) in range(97, 123): 8 result+=chr((ord(a[i])-97+5)%26+97) 9 else: 10 result += a[i] 11 return result 12 def decoder(a): 13 """解码加密文本""" 14 result = '' 15 for i in range(len(a)): 16 if ord(a[i]) in range(65, 91): 17 result+=chr((ord(a[i])-65+26-5)%26+65) 18 elif ord(a[i]) in range(97, 123): 19 result+=chr((ord(a[i])-97+26-5)%26+97) 20 else: 21 result += a[i] 22 return result 23 text = input("输入英文文本: ") 24 print(f"编码后的文本: {encoder(text)}") 25 print(f"对编码后的文本解码: {decoder(encoder(text))}")
1 def collatz(n): 2 x=[n] 3 while n!=1: 4 if n%2==0: 5 n=n/2 6 else: 7 n=3*n+1 8 x.append(int(n)) 9 return x 10 try: 11 n=int(input('Enter a positive integer:')) 12 if n<=0: 13 raise 14 except: 15 print('Error: must be a positive integer') 16 else: 17 print(collatz(n))