python中else与C/C++/Java的比较:
a. if与else语句的使用和C/C++/Java等语言的使用一致;
b. Python中存在循环体for/while与else的结合,而C/C++/Java中没有此用法。
for/while语句中else的执行条件:
for/while语句中的循环条件正常结束(包括:不满足循环条件),将会执行else语句;若在循环体中满足break和return条件退出循环体,将不会执行else语句。
代码示例:
a. if...else
x = 520
if 520 == x:
print(x, "I Love U", sep = ":", end = "!\n")
else:
print("I still love U!")
输出结果:
520:I Love U!
b. for...else
首先使用C/C++式的做法(Python语言实现),在一个列表中查找一个数字,若找到则输出索引,未找到输出“find not!”。
target = 6
is_found = False
nums = [1, 2, 3, 4, 5]
for i in range(len(nums)):
if nums[i] == target:
is_found = True
break
if is_found:
print("Index", i, sep = ":")
else:
print("Find not!")
输出结果:
Find not!
然后使用Python的for...else语句实现:
target = 6
nums = [1, 2, 3, 4, 5]
for i in range(len(nums)):
if nums[i] == target:
print("Index", i, sep = ":")
break
else:
print("Find not!")
输出结果:
Find not!
若把findNum 的值改为3,则输出结果:
Index:2
c. while...else
代码展示一种不满足循环条件的执行情况。
condition = 0
while(condition):
print ("while")
else:
print("loop end")
输出结果:
loop end