关于python3.x:python中else的三种用法

10次阅读

共计 1172 个字符,预计需要花费 3 分钟才能阅读完成。

python 中 else 能够在判断语句、循环语句和异样解决中应用。

判断语句 if … else …

a = 3
b = 2
if a > b:
    print("a 大于 b")
else:
    print("b 比 a 大")

循环语句 for/while … else …

当循环中未执行 break 语句即循环体失常完结则执行 else 语句,如果循环中执行了 break 则不执行 else 语句

for 循环 else

for i in range(3):
    print(i)
else:
    print("循环执行完")

输入

0
1
2
循环执行完 
for i in range(3):
    print(i)
    break
else:
    print('循环失常执行完')

输入

0

应用场景:质数判断

for num in range(10, 20):
    for i in range(2, num):
        if num % i == 0:
            j = num / i
            print("%d 等于 %d * %d" % (num, i, j))
            break
    else:
        print(num, '是一个质数')

输入

10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数 

while 循环

count = 0
while count < 5:
    print("%d is less than 5" % count)
    count += 1
else:
    print("%d is not less than 5" % count)

输入

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
count = 0
while count < 5:
    print("%d is less than 5" % count)
    count = 6
    break
else:
    print("%d is not less than 5" % count)

输入

0 is less than 5

异样解决

num1 = int(input("输出一个整数:"))
num2 = int(input("输出另外一个整数:"))
print('-'*20)
try:
    print("{}/{}=".format(num1,num2),num1//num2)
except ZeroDivisionError:
    print("输出非法,ZeroDivisionError")
else:
    print("输出非法")
print("程序完结")

代码执行,当没有异样时:

 输出一个整数:2
输出另外一个整数:1
----------------------------------------
2/1= 2
输出非法
程序完结 

产生异样时

 输出一个整数:2
输出另外一个整数:0
----------------------------------------
输出非法,ZeroDivisionError
程序完结 

https://www.jb51.net/article/…

正文完
 0