Python循环使用默认值,否则无限

时间:2016-06-03 12:28:36

标签: python python-2.7

我想创建一个循环,运行n次,其中:

  1. 'n'可以自由更改
  2. 'n'在没有传递值时应该有一个默认值
  3. 'n'应该在需要时永远运行
  4. 我目前的代码如下:

    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')停止?

2 个答案:

答案 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