【问题标题】:Loop being ignored by Python [closed]Python忽略循环[关闭]
【发布时间】:2015-01-28 15:31:32
【问题描述】:

我是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 似乎忽略了第一个循环(而选择 == y)。我是否忘记了一个步骤,还是我完全做错了?

【问题讨论】:

  • 你得到了什么输出,你期待什么?
  • 这是您的实际代码吗?我运行它并得到了NameError: name 'j' is not defined
  • 另外,混合缩进(4 个和 8 个空格)可能是个问题。
  • j的值是多少

标签: python class loops input


【解决方案1】:

我认为您在这里不需要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”以外的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多