首页 > 解决方案 > 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

标签: python

解决方案


代替 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)

推荐阅读