在循环时需要更短/更优雅的python解决方案

时间:2015-07-03 17:49:41

标签: python while-loop

我是一名新程序员,我正在努力解决这个问题:

带有循环和条件的用户输入。使用raw_input()来提示输入数字 介于1和100之间。如果输入符合条件,请在屏幕上指示并退出。 否则,显示错误并重新提示用户,直到收到正确的输入。

我的最后一次尝试终于奏效了,但我很想知道你更优雅的解决方案,我的记忆非常感谢你的所有投入:P

n = int(input("Type a number between 1 and 100 inclusive: "))
if 1 <= n <= 100:
    print("Well done!" + " The number " + str(n) + " satisfies the condition.")
else:
    while (1 <= n <= 100) != True:
        print("Error!")
        n = int(input("Type a number between 1 and 100: "))
    else:
        print ("Thank goodness! I was running out of memory here!")

1 个答案:

答案 0 :(得分:4)

您可以使用单个循环简化代码:

while True:
    n = int(input("Type a number between 1 and 100 inclusive: "))
    if 1 <= n <= 100:
        print("Well done!" + " The number " + str(n) + " satisfies the condition.")
        print ("Thank goodness! I was running out of memory here!")
        break # if we are here n was in the range 1-100 
    print("Error!") # if we are here it was not

如果用户输入正确的号码,您只需打印输出和break,否则将打印print("Error!")并再次询问用户。

另外,如果您使用的是python2,则输入相当于eval(raw_input()),如果您正在接受用户输入,则通常应按照问题中的说明使用raw_input

相关问题