我想创建一个循环,运行n次,其中:
我目前的代码如下:
n = raw_input('number of runs: ') # Get user input for 'n'
if n == '': # Empty input -> run the loop 1000 times (condition 2)
a = 1000 # Default value
elif n == 'oo': # Run the loop forever
a = 9000 # This value isn't important could be 1 aswell see while statement
else:
a = n # Run the loop for the value provided in raw_input
i = 1
while i <= int(a):
if n == 'oo':
a += 1 # If n=∞, increment 'a' after each iteration so the loop never stops
print i # Print 'i' to see if everything works like expected
i += 1
如何让这段代码更优雅(我觉得有更简单的方法)?如何在不使用键盘中断的情况下使循环(对于n ='oo')停止?
答案 0 :(得分:2)
使用for
- 循环和不同的迭代:
from itertools import count
n = raw_input('number of runs: ')
if n == '': #empty input-> run the loop 1000 times
counter = xrange(1, 1001)
elif n == 'oo': #run the loop forever
counter = count(1)
else:
counter = xrange(1, int(n)+1) #otherwise run the loop for the value provided above
for i in counter:
print i #print i to see if everything works like expected
答案 1 :(得分:0)
a = raw_input('Enter value for a: ')
try:
a = int(a)
except:
if a != 'oo':
a = 10000
if a == 'oo':
while True:
print "infinite"
pass
else:
while a != 0:
# do something
print a
a = a - 1