簡體   English   中英

如何限制 python 中的輸入嘗試?

[英]How do I limit input attempts in python?

我試圖限制我正在做的測驗中的嘗試,但不小心創建了一個無限循環。 我在這里做錯了什么?

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) + '.')

這是你應該如何處理它。 將問題和答案都傳遞給 function,以便它可以處理循環。 讓它返回這個問題的分數。

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}.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM