如何重置3个猜测计数器

时间:2018-04-11 21:07:41

标签: python

我正在用Python编写测验,用户有3次尝试让每个答案都正确。它倒计时到0,但是当它进入下一个问题时,它会继续倒计时并且不会重置为3个猜测,即第二个问题,答案是错误的并且它说“你还有-1猜测”,“你有-2猜测还剩“等等。如何让每个新问题重置为3次尝试?变量设置在顶部,代码运行在def wrong_answer中。代码如下:

score = 0
max_guesses = 3

def quiz(riddle):

    counter = 0

    while counter < 3:
        answer = input(riddle["question"] + " ")

        if right_answer(answer, riddle):
            global score
            score += 1
            print("Correct! Well done.\nYour score is",score)
            break

        else: 
            wrong_answer(answer)
            print("Your score is",score)
            counter +=1

def right_answer(answer, riddle):
    return answer == riddle["answer"]

def wrong_answer(answer): 
    if answer != riddle["answer"]:
        global max_guesses
        max_guesses -= 1
        print("Sorry", answer, "is wrong.")
        print ("You have", max_guesses, "guesses left")

with open("riddles.json") as riddles_file:
    riddles = json.load(riddles_file)

for riddle in riddles:
    quiz(riddle)

1 个答案:

答案 0 :(得分:0)

看起来你得到变量max_guesses和计数器混淆了。试试这个

score = 0
max_guesses = 3

def quiz(riddle):

    counter = 0

    while counter < max_guesses:
        answer = input(riddle["question"] + " ")

        if right_answer(answer, riddle):
            global score
            score += 1
            print("Correct! Well done.\n Your score is",score)
        else:
            counter +=1
            wrong_answer(answer, counter)
            print("Your score is",score)


def right_answer(answer, riddle):
    return answer == riddle["answer"]

def wrong_answer(answer, counter): 
    if answer != riddle["answer"]:
        print("Sorry", answer, "is wrong.")
        print ("You have", max_guesses - counter, " guesses left")

with open("riddles.json") as riddles_file:
    riddles = json.load(riddles_file)

for riddle in riddles:
    quiz(riddle)