实验4

task1.py
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_2.py

list1 = [1, 9, 8, 4] 

print( sorted(list1) )
print( sorted(list1, reverse=True) ) 
print( sorted(list1, True) )

task2_3.py

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))

task3.py

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()

task4.py

def list_generator(a,b,c=1):
    list = []
    while a <= b:
        list.append(a)
        a += c
    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)

task5.py

def is_prime(n):
    if n < 2:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


for x in range(2,21,2):
    for y in range(2,x):
        if is_prime(x-y) is True:
            print(f'{x} = {y} + {x-y}')
            break

task6.py

def encoder(a):
    list = []
    for i in a:
        a1 = ord(i)
        if 65 <= a1 <= 85 or 97 <= a1 <= 117:
            a1 += 5
        elif 85 <= a1 <= 90 or 118 <= a1 <= 122:
            a1 -= 21
        a2 = chr(a1)
        list.append(a2)
    return ''.join(list)


def decoder(b):
    list = []
    for v in b:
        b1 = ord(v)
        if 65 <= b1 <= 69 or 97 <= b1 <= 101:
            b1 += 21
        elif 70 <= b1 <= 90 or 102 <= b1 <= 122:
            b1 -= 5
        b2 = chr(b1)
        list.append(b2)
    return ''.join(list)


x = input('输入英文文本: ')
t = encoder(x)
print(f'编码后的文本: {t}')
z = decoder(t)
print(f'对编码后的文本解码: {z}')

task7.py

def collatz(n):
    if n % 2 == 0:
        return int(n/2)
    else:
        return int((3*n)+1)


try:
    x = int(input('Enter a positive integer: '))
    z = [x]
    if x <= 0:
        raise ValueError
    while True:
        y = collatz(x)
        z.append(y)
        x = y
        if x == 1:
            break
    print(z)
except ValueError:
    print('Error: must be a positive integer')

posted on 2022-05-07 19:34  好运来。  阅读(11)  评论(2编辑  收藏  举报