1. 程式人生 > 其它 >實驗4 函式與異常處理

實驗4 函式與異常處理

#task1
print(sum)
sum=42
print(sum)

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

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

不是

1.內建作用域

2.全域性作用域

3.區域性作用域

4.全域性作用域

#task2_1
def func1(a,b,c,d,e,f):
    return [a,b,c,d,e,f]

def func2(a,b,c,*,d,e,f):
    return [a,b,c,d,e,f]

def func3(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))
#task2_2
list1=[1,9,8,4]

print(sorted(list1)) print(sorted(list1,reverse=True)) print(sorted(list1,True)
#python內建函式sorted()中,引數reverse的傳遞方式必須使用關鍵字傳遞。
#task2_3
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
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 0 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,step=1):
    x=[]
    while a<=b:
        x.append(a)
        a+=step
    return x
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
def is_prime(n):
    if n<2:
        return False
    if n==2:
        return True
    else:
        for i in range(2,n):
            if n%i==0:
                return False
        return True
for j in range(2,21,2):
    for k in range(2,j):
        if is_prime(k)==True and is_prime(j-k)==True:
            print(j,'=',k,'+',j-k)
            break
#task6
def encode(s):
    a=[]
    for i in s:
        b=ord(i)
        if 97<=b<=117 or 65<=b<=85:
            b+=5
        if 117<=b<=122 or 86<=b<=90:
            b-=21
        a.append(chr(b))
    return ''.join(a)
def decode(s):
    a=[]
    for i in s:
        b=ord(i)
        if 102<=b<=122 or 70<=b<=90:
            b-=5
        elif 97<=b<=101 or 65<=b<=69:
            b+=21
        a.append(chr(b))
    return ''.join(a)
x=input('輸入英文文字:')
m=encode(x)
n=decode(m)
print('編碼後的文字:',m)
print('對編碼後的文字解碼:',n)
#task7
def collatz(n):
    a=[n]
    while n!=1:
        if n%2==0:
            n/=2
            a.append(int(n))
        else:
            n=3*n+1
            a.append(int(n))
    return a
try:
    n=eval(input('Enter a positive integer:'))
    if type(n)!=int or n<=0:
        raise ValueError
except ValueError:
    print('Error:must be a positive integer')
else:
    print(collatz(n))