无效输入后重新提供用户

时间:2017-10-23 21:44:24

标签: python python-3.x

这是我目前的代码:

# Imports random
import random

def game():
    """This holds the function for the game"""
    # Sets score to 0 intially
    score = 0
    wrong = 0
    # Questions
    questions = [{"question": "What is the price of a motorcycle?",
                  "answers": ["$1000", "$5000", "$10000", "$15000"],
                  "correct": "2"},
                 {"question": "How much is this toaster?",
                  "answers": ["$2", "$5", "$7"],
                  "correct": "2"},
                 {"question": "What is the price of a dog?",
                  "answers": ["$1", "$5000", "$100", "$70"],
                  "correct": "3"},
                 {"question": "How much is this electric pooper scooper?",
                  "answers": ["$200000", "$90", "$72.99"],
                  "correct": "3"},
                 {"question": "What is the price of apple sauce?",
                  "answers": ["$.50", "$5", "$3", "$1"],
                  "correct": "4"},
                 {"question": "is this lamborghini worth $100,000?",
                  "answers": ["True", "False"],
                  "correct": "1"},
                 {"question": "What is the price of a lifesize manaquin of batman?",
                  "answers": ["$2,530", "$500", "$100", "$45"],
                  "correct": "1"},
                 {"question": "How much is this 1 night vacation in idaho?",
                  "answers": ["$400", "$1000", "$95"],
                  "correct": "3"},
                 {"question": "What is the price of a honda Accord?",
                  "answers": ["$1000", "$9500", "$6000", "$18000"],
                  "correct": "4"},
                 {"question": "is this gold plated microwave worth over $2,000?",
                  "answers": ["True", "False"],
                  "correct": "1"}]
    # Shuffles questions
    random.shuffle(questions)
    print("Welcome to the price is right!")
    # loop for questions
    for question in questions:
        print(question["question"])
        for i, choice in enumerate(question["answers"]):
            print(str(i + 1) + ". " + choice)
        answer = input("Choose an answer: ")
        if answer == question["correct"]:
            print("That is correct!")
            score = score + 1
        else:
            print("That answer is incorrect!")
            wrong = wrong + 1
    # Score + Thank you message
    print()
    print()
    print("Your total score is:", score, "right, and", wrong, "wrong.")
    print("Thanks for playing the price is right!")
    print()
    main()

def main():
    """Calls all options"""
    while True:
        print("Welcome to the Price is Right! I'm your host, Python! What would you like to start with?!")
        print()
        option = input("Play, View Credits, or Quit:")
        if option.lower() == "play":
            return game()
        elif option.lower() == "view credits":
            print("Created by: Gennaro Napolitano and Mario DeCristofaro")
        elif option.lower() == "quit":
            exit()
        else:
            False
            print()
            print("Sorry, that is not a valid input, please try again!")
            print()

# Calls main
if __name__ == '__main__':
    main()

基本上,一旦游戏运行,用户必须通过选择1,2或3来选择正确的答案(或者有多少答案)。

如果他们为问题答案输入了错误的选项,我希望它能够重新提示用户输入。 E.g。

问题:

How much does this toaster cost?:
1. $2
2. $3
3. $4

用户输入:

A

计划回应:

Invalid response, please try again(Please choose "1", "2", or "3")

然后它会转发问题并给用户另一个机会重新输入答案。

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

真纳罗,

将输入指令放在循环中,例如:

while true:
    answer = input("Choose an answer: ")
    if int(answer) in [1,2,3]:
        break
    else:
        print("risposta non valida ;-)")

干杯 查理

修改

如果您在评论中报告的答案数量不固定,请执行以下操作:

while true:
    answer = input("Choose an answer: ")
    if int(answer) in question['answers']:
        break
    else:
        print("risposta non valida ;-)")

答案 1 :(得分:0)

你只需将问题部分放在一个循环中,如果答案是正确的,它将退出:

# loop for questions 
for question in questions: 
    print(question["question"]) 
    for i, choice in enumerate(question["answers"]):
        print(str(i + 1) + ". " + choice)
    answer = None
    while(answer != question["correct"]):
        if answer is not None:
             print("That answer is incorrect!")
             print("Try again")
             wrong = wrong + 1
        answer = input("Choose an answer: ")          
     print("That is correct!") 
     score = score + 1
# Score + Thank you message

编辑:我似乎误解了这个问题。

答案更像是(替换你的简单answer = input()):

answer = 0
while(answer < 1 or answer > len(question["answers"]):
    answer = int(input("Choose an answer: "))

答案 2 :(得分:0)

在检查玩家答案是否正确之前,您可以执行以下操作:

answer = input("Choose you answer: ")
while answer not in ['1', '2', '3']:
     print("Invalid response, please try again(Please choose '1', '2', or '3'")
     answer = input("Choose you answer: ")