python基础——异常处理、递归

 异常处理

while True:
    try:
        num1 = int(input('num1:'))
        num2 = int(input('num2:'))
        result = num1 + num2
    except ValueError as e: #捕获ValueError
        print(e)
    except Exception as e:  #捕获所有错误
        print(e)
    else:   #不出异常则执行else,可选项非必要
        print('else')
    finally:    #无论是否出现异常,都要执行finally,可选项非必要
        print('finally')

 

 自定义异常 

class testException(Exception): #自定义类,继承Exception

    def __init__(self,msg):
        self.message=msg

    def __str__(self):
        return self.message

try:
    raise testException('主动抛异常')    #raise主动抛异常
except testException as e:  #捕获上面的异常
    print(e)

 

断言

assert 1==1    #条件成立则继续执行,条件不成立则中断并抛异常
print('true')

 

 

递归

def func(n):
    n +=1
    if n>4:
        return "end"
    return func(n)

r=func(1)
print(r)

 

1*2*3*4*5*6*7

def func(n):
    if n >1:
        r=n*func(n-1)
        return r
    if n==1:
        r=1
        return r

ret=func(7)
print(ret)

 

#1*2*3*4*5*6*7
posted @ 2016-09-02 16:47  沄持的学习记录  阅读(399)  评论(0编辑  收藏  举报