使用带有try的while循环除了获取用户输入

时间:2015-04-30 18:06:01

标签: python while-loop try-catch raw-input except

当我在命令提示符下输入一个字母时,我的代码正在创建一个无限循环。我认为 len(sys.argv)> 1 导致问题,因为如果我在命令提示符处输入一个字母,则这将始终为true并且循环不会结束。不知道我怎么能解决这个问题...对这个新手的任何建议都会有所帮助。谢谢!

"""
Have a hard-coded upper line, n.
Print "Fizz buzz counting up to n", substituting in the number we'll be counting up to.
Print out each number from 1 to n, replacing with Fizzes and Buzzes as appropriate.
Print the digits rather than the text representation of the number (i.e. print 13 rather than thirteen).
Each number should be printed on a new line.
"""

# entering number at command line: working
# entering letter at command line: infinite loop
# entering number at raw_input: works, runs process
# entering letter at raw_input: working

import sys

n = ''

while type(n)!=int:
    try:
        if len(sys.argv) > 1:
            n = int(sys.argv[1])
        else:
             n = int(raw_input("Please enter a number: "))
    except ValueError:
        print("Please enter a number...")
        continue

print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
    if y % 5 == 0 and y % 3 == 0:
        print('fizzbuzz')
    elif y % 3 == 0:
        print('fizz')
    elif y % 5 == 0:
        print('buzz')
    else:
        print(y)`enter code here`

1 个答案:

答案 0 :(得分:0)

首先尝试强制转换值和索引错误:

import sys

try:
    n = int(sys.argv[1])
except (IndexError,ValueError):
    while True:
         try:
            n = int(raw_input("Please enter a number: "))
            break
         except ValueError:
            print("Please enter a number...")

print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
    if y % 5 == 0 and y % 3 == 0:
        print('fizzbuzz')
    elif y % 3 == 0:
        print('fizz')
    elif y % 5 == 0:
        print('buzz')
    else:
        print(y)

如果您实际上并未尝试接受命令行输入,请使用while True:

while True: 
     try:
        n = int(raw_input("Please enter a number: "))
        break # input was valid so break the loop
     except ValueError:
        print("Please enter a number...")

    print("Fizz buzz counting up to {}".format(n))
    for y in range(1,n+1):
        if y % 5 == 0 and y % 3 == 0:
            print('fizzbuzz')
        elif y % 3 == 0:
            print('fizz')
        elif y % 5 == 0:
            print('buzz')
        else:
            print(y)