python丰富的else语句

python的else可以跟哪些语句搭配呢?

1、跟if语句搭配:组成要么怎样,要么不怎样

def if_else():
    if 1 > 2:
        print('这是错误的')
    else:
        print('这才是正确的')

2、跟while和for语句搭配,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)

上面执行了break语句,就不会再去执行else语句

下面执行了break语句,就不会再去执行else语句

for i in range(10):
    if i == 5:
        print ('found it! i = %s' % i)
        break
else:
    print ('not found it ...')

3、跟异常处理语句:组成没有问题,那就干吧

try:
    int('abc')
except ValueError as reason:
    print('出错啦:'+ str(reason))
else:
    print('没有任何异常!')

上面的代码有异常,所以会执行出错啦的语句

下面的代码没有异常,会执行没有任何异常的语句

try:
    int('123')
except ValueError as reason:
    print('出错啦:'+ str(reason))
else:
    print('没有任何异常!')
原文地址:https://www.cnblogs.com/qinguodong/p/10893010.html