2015-07-03 62 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。如果你看到我打字,你會想知道如何;) –