Python 练习实例36

题目36:求100之内的素数。[内含break continue区别]

题目等同于《Python 练习实例12》,引用。

import math

lst = []
count = 1
for i in range(2, 101):
    s = int(math.sqrt(i))
    for m in range(2, s + 1):
        if i % m == 0:
            count = 0
            break
    if count == 1:
        lst.append(i)
    count = 1

print(lst)
print(len(lst))

话虽如此,还是看着break有点晕啊。于是查看了下continue与break的区别:
continue语句会立即跳到循环的顶端;break语句会立刻离开循环。

#continue时候的循环
for i in range(1, 4):
    print('o', 'i=',i)
    if 100 % i == 0:
        print('1', 'i=', i)
        continue
    print('2',u'结尾')  

continue时的输出
(‘o’, ‘i=’, 1)
(‘1’, ‘i=’, 1)
(‘o’, ‘i=’, 2)
(‘1’, ‘i=’, 2)
(‘o’, ‘i=’, 3)
(‘2’, ‘结尾’)

#break时候的循环
for i in range(1, 4):
    print('o', 'i=',i)
    if 100 % i == 0:
        print('1', 'i=', i)
        break
    print('2',u'结尾')    

break时的输出
(‘o’, ‘i=’, 1)
(‘1’, ‘i=’, 1)

你可能感兴趣的:(python,实例)