Python - 为什么在循环结束程序中获胜?

时间:2016-06-25 20:50:27

标签: python while-loop

所以这是我制作的一个小游戏,但当user_lives或comp_lives等于0时,它不会结束循环,我不明白为什么。

如果我将while循环设置为:while user_lives> 1或comp_lives> 1:

我也可以通过在两个elif语句的if语句中放置一个中断来修复它,但是我应该能够将while设置为True并使用无限循环。这有效,但我想知道为什么这个while循环不起作用。

任何帮助都会很棒!

from random import randint

user_lives = 3
comp_lives = 3

print("Welcome to the number guessing game!!!")
print("The game will choose a number between 0 and 10 and you must guess right before the computer does!!!")

while user_lives > 0 or comp_lives > 0:
    random_num = randint(0, 10)
    user_num = raw_input("Choose a number between 0 and 10: ")
    comp_num = randint(0, 10)
    print(random_num)
    print(comp_num)

    if int(user_num) == random_num and comp_num == random_num:
        print("Its a draw.")

    elif comp_num == random_num:
        print ("The computer has WON!")
        user_lives = user_lives - 1
        print("You have " + str(user_lives) + " lives left.")
        if user_lives == 0:
            print("GAME OVER.")         

    elif int(user_num) == random_num:
        print("You have WON!")
        comp_lives = comp_lives - 1
        print("The computer has " + str(comp_lives) + " lives left.")
        if comp_lives == 0:
            print("GAME OVER.")

    else:
        print("No one wins. Try again.")

1 个答案:

答案 0 :(得分:2)

您发布的代码的逻辑如下:

如果user_lives> 0,继续循环。要么 如果comp_lives> 0,继续循环。

你看到了问题吗?只有当usercomp生活<=0时,循环才会结束。

我想也许是一个更好的循环

while user_lives > 0 and comp_lives > 0: