实验四
作者:互联网
print(sum) sum=42 print(sum) def inc(n): sum = n+1 print(sum) return sum sum = inc(7) + inc(7) print(sum)
不是,line1、3、11是全局作用域,line7是函数作用域。
TASK2
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] 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))
list1 = [1,9,8,4] print(sorted(list1)) print(sorted(list1,reverse=True)) print(sorted(list1,True))
def func(a,b,c,/,*,d,e,f): return([a,b,c,d,e,f]) print(func(1,2,3,f=6,d=4,e=5))
TASK3
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 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()
TASK4
def list_generator(a, b, c=1): l = [a] while True: if c == None: a += 1 l.append(a) if a == b: break else: a += c l.append(a) if a == b: break return l list1 = list_generator(-5, 5) print(list1) list2 = list_generator(-5, 5, 2) print(list2) list3 = list_generator(1, 5, 0.5) print(list3)
TASK5
from math import sqrt def is_prime(n): if n == 1 or n == 0: return False for i in range(2, int(sqrt(n) + 1)): if n % i == 0: return False return True def gd(x): for i in range(2, x): if is_prime(i): if is_prime(x - i): print(x, '=', i, '+', x - i) return True return False i = 4 while (gd(i) and i < 20): i += 2
TASK6
def encoder(s): s=list(s) for i in range(len(s)): if s[i].isalpha(): if 'a'<=s[i].lower()<'v': s[i]=chr(ord(s[i])+5) else: s[i]=chr(ord(s[i])-21) else: s[i]=s[i] s=''.join(s) return s def decoder(s): s=list(s) for i in range(len(s)): if s[i].isalpha(): if 'a'<=s[i].lower()<='e': s[i]=chr(ord(s[i])+21) elif 'e'<s[i].lower()<='z': s[i]=chr(ord(s[i])-5) else: s[i]=s[i] s=''.join(s) return s s=input('输入英文文本: ') print(f'编码后的文本:{encoder(s)}') print(f'对编码后的文本解码:{decoder(encoder(s))}')
TASK7
def collatz(n): if n%2==0: return int(n/2) else: return int(n*3+1) try: l=[] x=int(input('Enter a positive integer: ')) l.append(x) if x<=0: raise while True: c=collatz(x) l.append(c) x=c if x==1: break print(l) except: print('Error: must be a positive integer')
标签:return,sum,实验,print,root1,def,root2 来源: https://www.cnblogs.com/AkieUp07/p/16254918.html