【问题标题】:Can't execute function in a while loop无法在while循环中执行函数
【发布时间】:2016-04-30 05:10:58
【问题描述】:

我在 while 循环中有以下代码:

while True:
    user_input = input("y or n")
    if user_input == "y":
        yes()
        break
    if user_input == "n":
        no()
        break

def yes():
    print("yes")

def no():
    print("no")

当我输入“y”时,会出现此消息,阻止函数执行。

NameError: name 'yes' is not defined

这是为什么?我该如何解决?

【问题讨论】:

  • 在while循环之前定义yes()
  • 道歉,但是提供什么理由将我的帖子的分数降低到-1? @TimCastelijns 你知道吗/
  • 可能是因为这是基本的并且之前已经问过

标签: python function input while-loop


【解决方案1】:

你必须在while之前定义函数yes()和no()。

像这样:

def yes():
    print("yes")

def no():
    print("no")

while True:
    user_input = input("y or n")
    if user_input == "y":
        yes()
        break
    if user_input == "n":
        no()
        break

这会很好用。

【讨论】:

    【解决方案2】:

    Python 从上到下执行代码,在遇到def 语句时创建函数对象。当它开始执行你的while 循环时,它还没有到达你的def yes(): 行,所以函数还不存在。

    将函数移到顶部,在 while 循环之前。

    或者,将循环移到另一个函数中,然后在定义yes 和no 函数之后调用该新函数。

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 2019-10-12
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      相关资源
      最近更新 更多