menu()
selection=float(input("Select a menu- Input a number:"))
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
exit
elif selection<=0 or selection>4:
print("There is no menu",end=" ")
print(selection)
else:
print("You have input a non digit value. Select again:")
它似乎只將小數識別為非數字值,但如果我穿來寫一個詞,它會說無法將字串轉換為浮點數 - 我該如何解決這個問題,我是編程新手
uj5u.com熱心網友回復:
嘗試這個
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = float(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
exit
elif selection<=0 or selection>4:
print("There is no menu",end=" ")
print(selection)
uj5u.com熱心網友回復:
我對您的代碼進行了一些更改并添加了一些行內注釋
# We start with None so that it enters the loop at least once
selection = None
# We create loop to keep asking the question until the user provides a number
while not selection:
selection=input("Select a menu- Input a number:")
# Check if the number is a decimal
if selection.isdecimal():
# I convert to an int since it's more natural
selection = int(selection)
# At this point, it will exit the loop
else:
# The user has intereed an incorrect value.
print("You have input a non integer value. Select again:")
# We empty selection so that it loops and asks the question again
selection = None
# Here we have an int
# If the selection is 1, 2 or 3, we display the menu. I use a list,
# but range(1, 3) would have worked too
if selection in [1, 2, 3]:
# Note I use an f-string here. You might not have learned about
# them yet. Requires at least Python 3.6
# This helps avoid repetition
print(f"::menu {selection}::")
elif selection==4:
# always call it like a function
exit()
else:
# Any other selection (remember, we know we have an int) should get this message
print(f"There is no menu {selection}")
uj5u.com熱心網友回復:
嘗試這個:
while True:
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = int(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
print('Exiting...')
quit()
else:
print("There is no menu",end=" ")
print(selection)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371061.html
上一篇:嵌套ifelse條件
