Python 里面,有种奇怪的语法,else 可以和 while 循环或者 for 循环搭配使用。
while...else 语法
while 判断条件:
语句1....
else:
语句2....
for...else 语法
for 遍历对象:
语句1....
else:
语句2....
这种奇怪的语法是说:
当 while/for 循环正常执行完的情况下,执行 else 输出;
如果当 while/for 循环中执行了跳出循环的语句,比如 break,将不执行 else 代码块的内容;
举个栗子
输入一个大于1的自然数,如果是质数,显示其为质数,否则打印出其最大约数。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
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("请输入一个大于1的整数: "))
showMaxFactor(num)
执行脚本打印结果如下:
[root@python ~]# ./showMaxFactor.py
请输入一个大于1的整数: 100
100的最大约数是50
[root@python ~]# ./showMaxFactor.py
请输入一个大于1的整数: 101
101是一个质数!