python - Python错误答案输入
问题描述
我想这样做,所以我的菜单的工作方式是,如果输入字母或输入正确答案以外的任何内容,我的脚本不会突然结束,它会要求输入正确的选项。任何人都可以帮我这样做吗?这是我到目前为止的代码:
#variables for password entry
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
#password entry code
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("out of guesses!")
else:
print("You are into the secret lair!")
#Menu code
def menu(menu):
print("--------------------------\nMenu\n--------------------------\n1.Secret
Sauce\n2.More secret stuff\n3.Even more secret stuff\n4.Exit")
choice = int(input("--------------------------\nENTER CHOICE: "))
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4:
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
#exit loop for the def
running = True
while running:
menuChoice = menu(menu)
if menuChoice == False:
print("\nGoodbye")
running = False
解决方案
代替
choice = int(input("--------------------------\nENTER CHOICE: "))
您可以执行以下操作:
choice = input("--------------------------\nENTER CHOICE: ")
然后在它之后我们需要检查字符串是否为数字,这样您就可以安全地将其转换为“int”类型。
if choice.isdigit():
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4 or choice != (1,2,3,4):
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
推荐阅读
- docker - 如何在 Digital Ocean 液滴上运行 docker 镜像?
- javascript - 在发射中异步返回数据
- angular - httpClient put 请求显示错误
- php - Laravel 5.6 和 Algolia 搜索返回空结果
- php - Codeigniter - 多个 insert_id
- java - Java RMI 和高级多线程
- python - 在 Pandas 列中选择日期子集
- javascript - 在 Highcharts 中为堆积柱形图中的列禁用堆栈标签
- django - Django - 如何为 ImageField 模型设置默认图像
- batch-file - 如何使用批处理脚本从文件中获取特定单词?