通过遍历元素循环
for letter in 'Python':
print("当前字母", letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print("当前水果", fruit)
通过序列索引迭代
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print("当前水果", fruits[index])
循环使用else语句
在Python中,for...else中的for语句和普通for循环没有区别,else中的语句会在循环正常执行完(即for不是通过break跳出而中断的)的情况下执行,while...else也是一样。
for num in range(10, 20): # 迭代10到20之间的数字
for i in range(2, num): # 根据因子迭代
if num % i == 0: # 确定第一个因子
j = num / i # 计算第二个因子
print("%d 等于 %d * %d" % (num, i, j))
break # 跳出当前循环
else: # 循环的else部分
print(num, "是一个质数")
while...else在循环条件为false时执行else语句块。
count = 0
while count < 5:
print(count, " is less than 5")
count += 1
else:
print(count, " is not less than 5")
本文介绍了Python中for循环的基本用法,包括遍历字符串、列表等数据结构,以及如何利用序列索引来迭代元素。此外,还详细解释了for...else和while...else的特殊用法,展示了如何判断质数等实用案例。
1496

被折叠的 条评论
为什么被折叠?



