2015-07-03 41 views
-1

我是一个新的程序员,我用了一个解决这个问题所困扰:需要较短/更优雅的解决方案,以蟒蛇while循环

用户输入与循环和条件。使用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!") 

回答

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 

如果用户输入正确的数字或​​将打印print("Error!")并且用户将再次被询问,您只需打印输出和break

请注意,如果您使用的是python2,输入等同于eval(raw_input()),如果您正在进行用户输入,您应该通常按照您的问题中的说明使用raw_input

+0

您键入的快捷,+1 – paisanco

+0

@ paisanco。如果你看到我打字,你会想知道如何;) –