循环被 Python 忽略

Loop being ignored by Python

我是 python 的初学者,在尝试自己编写一个简单的程序时,我 运行 遇到了这个问题:

class y:
    def out(self):
            print("restarting")
choice = y
choice.out
while choice == y:    # loop until user stops
    while j >= 0:   # loop until j < 0
            print('lives:', j)
            j = j - 1
    print('out of lives!')
    print('restart?')
    choice = input(' Y or N ')    # Ask user to restart or not

一切都运行一次,但 Python 似乎忽略了第一个循环(而 choice == y)。我是不是忘记了一个步骤,还是我完全做错了?

我认为您在这里不需要 class y。如果你只想循环直到 choice 不是字符 "y",那么你可以使用普通字符串。

choice = "y"
while choice == "y":    # loop until user stops
    j = 3
    while j >= 0:   # loop until j < 0
        print('lives:', j)
        j = j - 1
    print('out of lives!')
    print('restart?')
    choice = input(' Y or N ')    # Ask user to restart or not

结果:

lives: 3
lives: 2
lives: 1
lives: 0
out of lives!
restart?
 Y or N y
lives: 3
lives: 2
lives: 1
lives: 0
out of lives!
restart?
 Y or N n

程序循环,直到用户输入 "y" 以外的值。