如果这是一个愚蠢的问题,请原谅我,但由于问题的措辞,我到处搜索并找不到答案。
有没有办法在 Python 的 if 语句中使用“非数字”值?
比如说你有一个这样的菜单:
For free examples - Press 1
For worse free examples - Press 2
我想写一个 if 语句或 elif 语句,它说的是:
elif menu_Choice != #:
print("This menu only accepts numerical input. Please try again.\n")
menu_Choice = input("\n")
我可以这样做吗?如果是,怎么办?
请您参考如下方法:
为什么不这样说:
if menu_choice == "1":
do this
elif menu_choice == "2":
do this
else:
print("Invalid input...!")
你也可以这样做:
menu_choice = ""
while menu_choice not in ["1", "2"]: # not ideal with lots of choices
print("This menu only accepts numerical input. Please try again.\n")
menu_Choice = input("\n")
然后去你的if语句
编辑:
关于您的评论,您可以:
# you could make range as big as you like..
choices = [str(i) for i in range(1, 11)] #['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
while menu_choice not in choices:
print("That input wasn't valid. Please try again.\n")
menu_Choice = input("\n")
我用 list comprehension 制作了列表 choices
