# 实验四

print(sum)
sum = 42
print(sum)

def inc(n):
sum = n+1
print(sum)
return sum

sum = inc(7) + inc(7)
print(sum)

line1作用域为line1

line3作用域为line2

line7作用域为line6

line11作用域为line10

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,d=4,e=5,f=6))

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(x,y,z=1):
list=[]
while x<=y:
list.append(x)
x+=z
return list
list1 = list_generator(-5, 5)
print(list1)
list2 = list_generator(-5, 5, 2)
print(list2)
list3 = list_generator(1, 5, 0.5)
print(list3)

def is_prime(x):
if x==0:
return False
elif x==1:
return False
else:
for j in range(2,x):
if x%j==0:
return False
else:
return True
k=0
for n in range(4,20,2):
for m in range(1,n):
n2=n-m
if is_prime(n2) and is_prime(m) and m<=n2:
print(n,"=",m,"+",n2)
k+=1

task6def encoder(x):
x = list(x)
for i in range(len(x)):
if('v' <= x[i].lower() <= 'z'):
x[i] = chr(ord(x[i]) - 21)
elif('a' <= x[i].lower() <= 'v'):
x[i] = chr(ord(x[i]) + 5)
x = ''.join(x)
return x
def decoder(x):
x = list(x)
for i in range(len(x)):
if('a' <= x[i].lower() <= 'e'):
x[i] = chr(ord(x[i]) + 21)
elif('e' < x[i].lower() <= 'z'):
x[i] = chr(ord(x[i]) - 5)
x = ''.join(x)
return x
y = input('输入英文文本；')
print('编码后的文本：{}'.format(encoder(y)))
print('对编码后的文本解码：{}'.format(decoder(encoder(y))))

def collatz(x):
if x%2==0:
return int(x/2)
else:
return int(3*x+1)
list=[]
try:
n=eval(input('Enter a positive integer:'))
if n<=0:
raise
elif int(n)!=n:
raise
while True:
if n!=1:
list.append(n)
n=collatz(n)
else:
list.append(n)
break
print(list)
except:
print('Error: must be a positive integer')

posted @ 2022-05-09 12:36  10309  阅读(5)  评论(0编辑  收藏  举报