python中else语句与with语句

else语句

if-else语句:

与while语句和for循环配合使用:

else语句只有在循环顺利完成后执行,如果循环执行过程中使用break等跳出循环则else语句不会被执行

求一个数的最大约数:

def showMAXFactor(num):
    count = num // 2
    while count > 1:
        if num %count == 0:
            print('%d 的最大约数是:%d' % (num,count))
            break
        count -= 1
    else:
        print('%d是素数' % num)

num=int(input('请输入一个数:'))
showMAXFactor(num)

与try-except配合使用:

当try中,没有任何异常时,执行else语句,否则不执行

try:
    sum=int('abc')
except ValueError as reason:
    print('出错了:' + str(reason))
else:
    print('没有错误')

try:
    sum=int('123')
except ValueError as reason:
    print('出错了:' + str(reason))
else:
    print('没有错误')

with语句

with语句抽象出了文件操作中频繁使用的try-except-finally语句等的相关细节,可以自动关闭文件,在文件操作中使用with语句,可以大大的减少代码量。

try:
    with open('www.txt','w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错了:' + str(reason))

猜你喜欢

转载自blog.csdn.net/wpqdameimei/article/details/84137175