尝试使用python退出while循环

时间:2018-10-06 22:07:41

标签: python python-3.x

我是Python的新手,我制作了一个随机数字猜谜游戏。我遇到的问题是,当我达到0个生命时,我无法让程序退出while循环,而是告诉我我有-1个生命或-2个生命,等等。我查看了一下代码,但是我很挣扎看看我的逻辑/编程中的缺陷。任何帮助,将不胜感激!

from random import randint


randomnumber = randint(1, 30)

print("Welcome to the number guessing game!")

game = False
lives = 3

while not game or lives == 0:

    playerguess = int(input("Please enter a number between 1 and 30: "))

    if playerguess > 30 or playerguess < 1:
        print("Please only enter numbers between 1 and 30")
    elif playerguess == randomnumber:
        print("Correct!")
        game = True
    elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
        lives -= 1
        print("You were so close! You now have", lives, "lives remaining!")
    else:
        lives -= 1
        print("Not even close! You now have", lives, "lives remaining!")

if game:
    print("Congratulations you won with ", lives, "lives remaining!")
else:
    print("Sorry you ran out of lives!")

3 个答案:

答案 0 :(得分:1)

更改为此while not game and lives > 0

您当前的语句while not game or lives == 0,意味着如果生命不为0 not game,则循环可以继续,因为您可以用尽生命而无需更改gameTrue的循环将不会退出。

只有在您的生命超过0且not game可以解决问题后,此新条件才允许运行游戏。

Congratulations you won with  3 lives remaining!
...
Not even close! You now have 0 lives remaining!

对不起,您没钱了!

答案 1 :(得分:0)

您的条件不正确:

while not game and lives > 0:

您想在游戏未完成(not game)且生命数大于0(lives > 0)时循环播放。

答案 2 :(得分:0)

您应该将while条件提高到while not game and lives > 0或在while循环中添加一个break命令,直到到达lives < 1时才会调用:

...
while not game:

    playerguess = int(input("Please enter a number between 1 and 30: "))

    if playerguess > 30 or playerguess < 1:
        print("Please only enter numbers between 1 and 30")
    elif playerguess == randomnumber:
        print("Correct!")
        game = True
    elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
        lives -= 1
        print("You were so close! You now have", lives, "lives remaining!")
    else:
        lives -= 1
        print("Not even close! You now have", lives, "lives remaining!")

    #get out of loop if player died
    if lives < 1:
        break

if game:
...