Python学习笔记——esle和with 语句

1. else与while组合

def showMaxFactor(num):
    count = num // 2
    while count > 1:
        if num % count == 0:
            print('%d最大的约数是%d' % (num,count))
            break
        count -= 1
    # 如果循环中的语句全部执行完,没有中途跳出,则会执行else中的语句
    else:
        print('%d是素数!' % num)
        
num = int(input('请输入一个数:'))
showMaxFactor(num)
请输入一个数:11
11是素数!

2. else与try组合

try:
    int('abc')
except ValueError as reason:
    print('出错啦!' + str(reason))
else:
    print('没有任何异常!')
出错啦!invalid literal for int() with base 10: 'abc'
try:
    int('123')
except ValueError as reason:
    print('出错啦!' + str(reason))
else:
    print('没有任何异常!')
没有任何异常!

3. with语句

# 用finally语句关闭文件
try:
    f = open('data.txt','w')
    for each_line in f:
        print(each_line)
except OSError as reason:
    print('出错啦:' + str(reason))
finally:
    f.close()
# 由于文件本来不存在,且未写入数据,所以文件不可读
出错啦:not readable
# 与上面的代码功能相同,用于关闭文件
try:
    with open('data.txt','w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错啦:' + str(reason))

出错啦:not readable

    原文作者:没有故事的土鳖
    原文地址: https://www.jianshu.com/p/6ce52a00c7bd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞