Jckxxlaw
Jckxxlaw

Reputation: 391

How to run a python while loop until a variable is created?

I want a while loop in python to run until a variable is created, like so:

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

How to do?

Upvotes: 0

Views: 5307

Answers (3)

martineau
martineau

Reputation: 123531

An almost Pythonic way to do it:

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

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

print(choice)

I say "almost" because it would be more so to just put the try/except in the loop itself:

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

Upvotes: 0

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35826

There is no concept of exists() in Python (like in other programming languages). We usually use a bool evaluation and initialize the variable in question with a falsish value, like in the following approach:

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

search() in this case represents your method of choice, which at some point changes the value bound to found to a trueish one.

Upvotes: 0

Yossi
Yossi

Reputation: 12110

while 'choice' not in locals():
    # your code here

But you are doing it the wrong way. You better initialize the variable before the loop like this:

choice = None
while choice is None:
    # your code

Upvotes: 3

Related Questions