python for循环语句

通过遍历元素循环
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")

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值