2016-09-17 24 views
0

我有這樣的代碼:如何循環嘗試和除ValueError代碼,直到用戶輸入coorect值?

try: 
    phone = int(input("Enter your telephone no. : ")) 
except ValueError: 
    print("You must enter only integers!") 
    phone = int(input("Enter your telephone no. : ")) 

我希望用戶輸入他們的電話號碼。但是,如果他們輸入除整數以外的任何內容,則會出現一條錯誤消息,說您只能輸入整數。我想要做的就是循環這段代碼,以便每當用戶輸入一個非整數值時就會出現錯誤消息。到目前爲止,所有這些代碼都只是第一次打印錯誤消息。在第一次用戶輸入非整數值後,程序將中斷。

請提供一個不太複雜的解決方案...我只是一個初學者。 我在想你的意思是使用一個while循環,但我不知道如何?

回答

2

我認爲最好的辦法就是把它包起來的函數:

def getNumber(): 
    while True: 
     try: 
      phone = int(input("Enter your telephone no. : ")) 
      return phone 
     except ValueError: 
      pass 
1

你可以用這樣的

while True: 
    try: 
     phone = int(input("Enter your telephone no. : ")) 
    except ValueError: 
     print("You must enter only integers!") 
    else: # this is executed if there are no exceptions in the try-except block 
     break # break out of the while loop 
+0

對不起while循環做它沒有工作 –

+0

你是什麼意思它「沒有工作」? – JakeD

相關問題