在python中限制循环重复

时间:2014-04-06 02:46:45

标签: python loops

我有一个使用循环的程序,但事情是,如何使循环只重复给定的次数?下面的代码示例。

while True:
    print "This should be reprinted only ten times"

如何让这段代码只重复十次或任何给定的次数?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

for i in range(10):
    print "This should be reprinted only ten times"

OR

i=0
while i < 10:
    print "This should be reprinted only ten times"
    i+=1

或简单

print "This should be reprinted only ten times\n"*10

对于范围和随机数:

from random import randint
num = randint(5,10)
print "This should be reprinted only {} times\n".format(num)*num