def menu():
print("1. Create new User")
print("2. View User")
print("3. Update User")
print("4. Quit ")
menu()
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
selection=input("Select a menu- Input a number:")
else:
selection = int(selection)
if selection==1:
print("::menu 1::")
newName = input("Input first name : ")
newSurname = input("Input last name : ")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
print("you have logged out")
else:
print("There is no menu",end=" ")
print(selection)
print()
menu()
selection=input("Select a menu- Input a number:")
因此,當我運行代碼并首先輸入錯誤的值(非整數)然后輸入不在選單中的數字時,我希望它能夠讓我輸入另一個數字,例如正確的數字,例如 1 但它似乎沒有在那之后什么都不做,我不知道如何解決它有人可以提供幫助。它僅在我首先執行時才承認 1-4,但在任何錯誤值之后都不承認。
uj5u.com熱心網友回復:
您應該使用回圈來驗證輸入。當用戶輸入有效內容時打破回圈并繼續。
selection=int(input("Select a menu- Input a number:"))
while selection not in (1,2,3,4):
selection=int(input("Invalid number...Select a menu- Input a number:"))
請注意,如果輸入的不是整數,這將引發錯誤。如果你想處理它,你應該使用一個try陳述句。
uj5u.com熱心網友回復:
之所以沒有發生這種情況,是因為您應該將整個選單包裝在一個 while 回圈中。如果輸入的數字不在選單中,那么它只會通過呼叫menu()再次顯示選單,然后它會要求您再插入一個數字selection=input("Select a menu- Input a number:"),然后停止運行。接下來沒有其他指令要執行。
def menu():
print("1. Create new User")
print("2. View User")
print("3. Update User")
print("4. Quit ")
menu()
selection=input("Select a menu- Input a number:")
while selection != 4:
if not selection.isdigit():
print("You have input a non digit value. Select again:")
selection=input("Select a menu- Input a number:")
else:
selection = int(selection)
if selection==1:
print("::menu 1::")
newName = input("Input first name : ")
newSurname = input("Input last name : ")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
print("you have logged out")
break
else:
print("There is no menu",end=" ")
print(selection)
print()
menu()
selection=input("Select a menu- Input a number:")
uj5u.com熱心網友回復:
您可以撰寫一個小函式來驗證您的輸入。也許是這樣的:
def validate(selection):
while not selection.isdigit():
selection = input("You have input a non digit value. Select again:")
return int(selection)
def get_name(i):
print("::menu {}::".format(i))
newName = input("Input first name : ")
newSurname = input("Input last name : ")
return newName, newSurname
def menu():
print("1. Create new User")
print("2. View User")
print("3. Update User")
print("4. Quit ")
menu()
selection = input("Select a menu- Input a number:")
selection = validate(selection)
if selection is 1:
newName, newSurname = get_name(selection)
elif selection in (2,3):
print("::menu {}::".format(selection))
elif selection is 4:
print("you have logged out")
else:
print("There is no menu {}".format(selection))
menu()
selection=input("Select a menu- Input a number:")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369979.html
