python3--异常处理及习题

#异常处理try..except...
#打开一个不存在的文件
try:
    with open('non_exist.txt',mode='r') as f1:
        print('file opend!')
        f1.close()
except:
    print('file is not exist!')
print('DONE!')


#使用异常处理猜数字游戏,输入非整数,抛出异常
import random
flag = False
while(flag == False):
    try:
        result = random.randint(1,101)
        number = int(input('input you number:'))
        if number == result:
            print('bingo!')
            flag = True
        elif number > result:
            print('you have big number!')
        else:
            print('you have small number!')
    except:
        print('please input integer!')



你可能感兴趣的:(python菜鸟之路)