一般来说,else是与if或elif相搭配使用的,其实也可以与循环和try-except语法使用。
else与for循环搭配
示例:尝试找到n不大于max的除数
def find_divisor(n, max):
for i in range(2, max + 1):
if n % i == 0:
print(i, 'divides evenly into', n)
break
else:
print('no divisor found')
find_divisor(49, 6)
find_divisor(49, 7)
no divisor found
7 divides evenly into 49
else与while循环搭配
def find_num(m, get_str):
a = 0
word = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
while a < m:
if get_str == word[a]:
print('这个字母在26字母顺序中第', a + 1, '个')
break
a += 1
else:
print('不在m的范围内,请扩大搜索范围')
find_num(8, 'f')
find_num(4, 'f')
这个字母在26字母顺序中第 6 个
不在m的范围内,请扩大搜索范围
else与try-except搭配
def try_else(num1, num2):
try:
result = num1 / num2
except ZeroDivisionError:
print("除数不能为零")
else:
print("结果为: ", result)
try_else(4, 0)
try_else(4, 2)
除数不能为零
结果为: 2.0