试图让我的代码只输入数字值,如果它输入一个非数字值,它会打印你输入了一个非数字值,但它不起作用
Posted
技术标签:
【中文标题】试图让我的代码只输入数字值,如果它输入一个非数字值,它会打印你输入了一个非数字值,但它不起作用【英文标题】:Trying to get my code to input only digit values and if it inputs a non digit value it prints You have input a non digit value but its not working 【发布时间】:2022-01-02 23:02:24 【问题描述】:它似乎只将小数识别为非数字值,但如果我戴上写一个单词,它会说无法将字符串转换为浮点数-我该如何解决这个问题,我是编程新手
【问题讨论】:
您应该阅读try
和except
作为捕获此类错误的方法。
【参考方案1】:
试试这个
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)
【讨论】:
【参考方案2】:我对您的代码进行了一些更改并内联添加了一些 cmets
# 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")
【讨论】:
【参考方案3】:试试这个:
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)
【讨论】:
以上是关于试图让我的代码只输入数字值,如果它输入一个非数字值,它会打印你输入了一个非数字值,但它不起作用的主要内容,如果未能解决你的问题,请参考以下文章