【问题标题】:How to run a python while loop until a variable is created?如何在创建变量之前运行python while循环?
【发布时间】:2015-01-22 20:57:18
【问题描述】:

我希望在 python 中运行一个 while 循环,直到创建一个变量,如下所示:

while choice doesn't exist:
  do stuff involving choice
end while loop

怎么办?

【问题讨论】:

  • choice = None初始化怎么样?
  • 有没有不初始化的方法,比如 while 选择 False 什么的?
  • 否,当您使用 choice 启动 while 循环时,它必须被初始化。但正如 Tobias 所说,您可以将其设为 None 并说 while choice == None:
  • @Gullydwarf:为了与None进行比较,最好使用身份运算符(is)。
  • 如果do stuff involving choice不存在,你会怎么做?

标签: python while-loop


【解决方案1】:
while 'choice' not in locals():
    # your code here

但是你做错了。你最好像这样在循环之前初始化变量:

choice = None
while choice is None:
    # your code

【讨论】:

  • 如果 choice 被定义,第一个在函数内部不起作用,但在它外部。
【解决方案2】:

Python 中没有exists() 的概念(就像在其他编程语言中一样)。我们通常使用 bool 评估并使用假值初始化有问题的变量,例如以下方法:

found = False
while not found:
    found = search()

search() 在这种情况下代表您选择的方法,它在某些时候会将绑定到 found 的值更改为真实值。

【讨论】:

  • 嗯,有hasattr,但我认为你不能将它用于模块级变量。
  • @tobias_k:当然,总会有黑客攻击。即使在这种情况下,显然我们也有办法检查模块级别名称的存在。因为:Python 中的所有名称都存储在字典中。
【解决方案3】:

一种几乎是 Pythonic 的方式:

def exists(variable):
    try:
        eval(variable)
    except NameError:
        return False
    return True

while not exists('choice'):
    choice = 42

print(choice)

我说“几乎”是因为将try/except 放在循环本身中会更好:

done = False
while not done:
    try:
        # do stuff with choice
        choice = 42
        print(choice)
        done = True
    except NameError:
        pass

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2019-09-03
    • 2017-05-19
    • 2012-06-17
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多