需要 shorter/more python while 循环的优雅解决方案

Need shorter/more elegant solution to 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!")

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

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在你的问题中。