为什么我的Python代码不会在循环中离开?

时间:2017-06-11 18:37:07

标签: python-3.x while-loop

我应该编写一个会询问随机减法问题的游戏。当用户可以输入0继续下一个问题,或者-1退出。当它退出时,它将打印用户分数并询问他们是否想再次播放。如果用户连续获得3个错误答案,游戏应该结束。但是我似乎可以让我的while循环工作。它达到3然后才重置。它似乎永远不会结束游戏,并询问用户是否想再玩一次。

我错过了什么?

import random

highscore = 0

playAgain = 'Y'
while playAgain == 'Y':

correctCount = 0
totalCount = 0
wrongCount = 0

cont = 0
if wrongCount >=3:
    playAgain = eval(input("Do you want to play again? Y for Yes and N for No: "))
while wrongCount < 3:

    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    if num1 < num2:
        num1, num2 = num2, num1
        answer = eval(input("What is "+str(num1)+" - "+str(num2)+" ?\n"))
        if num1 - num2 == answer:
            print("You are correct!\n")
        totalCount += 1
        correctCount += 1

        #cont = int(input("Do you want to continue? 0 for Yes and -1 for No: "))
        if num1 - num2 != answer:
            print("Sorry, that answer is incorrect\n")
        totalCount += 1
        wrongCount += 1

score = (correctCount / totalCount) * 100
print("You answered "+correctCount+" questions right, out of a total of 
"+totalCount+" questions.\nYour score is: "+score)

if score > highscore:
print("You scored the new high score!")
playAgain = eval(input("Do you want to play again?"))

1 个答案:

答案 0 :(得分:0)

这就是你想要的一切,享受...... 请注意使用if条件的correctCount和wrongCount。

import random

highscore = 0

playAgain = 'Y'
while playAgain == 'Y':

    correctCount = 0
    totalCount = 0
    wrongCount = 0

    cont = 0
    # if wrongCount >=3:
    #     playAgain = int(input("Do you want to play again? Y for Yes and N for No: "))
    while wrongCount < 3:

        num1 = random.randint(0,9)
        num2 = random.randint(0,9)
        if num1 < num2:
            num1, num2 = num2, num1
            answer = int(input("What is " + str(num1)+ " - " + str(num2) + " ?\n"))
            if num1 - num2 == answer:
                print("You are correct!\n")
                correctCount += 1
            if num1 - num2 != answer:
                print("Sorry, that answer is incorrect\n")
                wrongCount += 1
            totalCount += 1

            #cont = int(input("Do you want to continue? 0 for Yes and -1 for No: "))            

    score = (correctCount / totalCount) * 100
    print("You answered "+str(correctCount)+" questions right, out of a total of "+str(totalCount)+" questions.\nYour score is: "+str(score))

    if score > highscore:
        highscore = score
        print("You scored the new high score!")
    playAgain = raw_input("Do you want to play again? Y for Yes and N for No: ")