简体   繁体   中英

How do I limit input attempts in python?

I am trying to limit the attempts in a quiz I am making, but accidentally created an infinte loop. What am I doing wrong here?

score = 0
print('Hello, and welcome to The Game Show')


def check_questions(guess, answer):
    global score
    still_guessing = True
    attempt = 3
    while guess == answer:
        print('That is the correct answer.')
        score += 1
        still_guessing = False
    else:
        if attempt < 2:
            print('That is not the correct answer. Please try again.')
        attempt += 1
    if attempt == 3:
        print('The correct answer is ' + str(answer) + '.')


guess_1 = input('Where was Hitler born?\n')
check_questions(guess_1, 'Austria')
guess_2 = int(input('How many sides does a triangle have?\n'))
check_questions(guess_2, 3)
guess_3 = input('What is h2O?\n')
check_questions(guess_3, 'water')
guess_4 = input('What was Germany called before WW2?\n')
check_questions(guess_4, 'Weimar Republic')
guess_5 = int(input('What is the minimum age required to be the U.S president?\n'))
check_questions(guess_5, 35)
print('Thank you for taking the quiz. Your score is ' + str(score) + '.')

Here is how you should handle it. Pass both the question and the answer into the function, so it can handle the looping. Have it return the score for this question.

score = 0
print('Hello, and welcome to The Game Show')

def check_questions(question, answer):
    global score
    for attempt in range(3):
        guess = input(question)
        if guess == answer:
            print('That is the correct answer.')
            return 1
        print('That is not the correct answer.')
        if attempt < 2:
            print('Please try again.')
    print('The correct answer is ' + str(answer) + '.')
    return 0


score += check_questions('Where was Hitler born?\n', 'Austria')
score += check_questions('How many sides does a triangle have?\n', '3')
score += check_questions('What is H2O?\n', 'water')
score += check_questions('What was Germany called before WW2?\n', 'Weimar Republic')
score += check_questions('What is the minimum age required to be the U.S president?\n', '35')
print(f"Thank you for taking the quiz. Your score is {score}.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM