for循环与循环的else

python3:for循环的else语句

代码:

#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-

from math import sqrt

total = 0
for num in range(2, 50):
    print(F'{num}:')
    for i in range(2, int(sqrt(num))+1):  # from 2 to int(sqrt(num)).
        if num % i == 0:  # the first factor
            j = num // i  # the second factor
            print ('  %d = %d * %d' % (num, i, j))
            break
        else:
            print(F'  {num} % {i} != 0')
            pass
    else:  # else of for loop
        print(num, '是一个质数')
        total += 1
    print("从%d到%d一共有%d个质数。" %(2, num, total))

结果:

2:
2 是一个质数
从2到2一共有1个质数。
3:
3 是一个质数
从2到3一共有2个质数。
4:
  4 = 2 * 2
从2到4一共有2个质数。
5:
  5 % 2 != 0
5 是一个质数
从2到5一共有3个质数。
6:
  6 = 2 * 3
从2到6一共有3个质数。
7:
  7 % 2 != 0
7 是一个质数
从2到7一共有4个质数。
8:
  8 = 2 * 4
从2到8一共有4个质数。
9:
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值