在python中限制循环重复

2024-10-02 22:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用循环的程序,但问题是,如何使循环只重复给定的次数?下面的代码示例。你知道吗

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

我怎样才能使这个代码只重复10次,或者任何给定的次数?你知道吗


Tags: 代码程序true示例onlybethis次数
1条回答
网友
1楼 · 发布于 2024-10-02 22:31:41

你可以做:

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

或者

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

相关问题 更多 >