Miller
Miller

Reputation: 23

Nested 'While' loop as a function

def Commands():
            command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
            elif command == "Run" :
                restart = True
                break
if groups == 4 :
    restart = True
    while restart :
        restart = False
        Commands()

How can I get this function to work properly? The "restart = True" "break" lines do not start the previous "while" loop again. I am using the commands in multiple "if" statements and want to avoid 80+ lines of code repeated for each one. I have removed the unrelated code that works properly.

Upvotes: 1

Views: 647

Answers (3)

Instead of trying to use a global variable or a break outside a loop (your current usage should have given a syntax error) - you should just return a Boolean value and evaluate the return value of the function, like:

def Commands():
    command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
    if command.lower() == "run" :
        return True
        # changed this to use lower (so it sees run or Run or RUn)
        # and now it just returns a True value to say - keep going
    return False 
    # assuming that everything else means break out of loop just return False if not "Run"

while True:
    if not Commands():
        break

print "We're out"

You could also just set the while loop to while Commands(): and remove the break as shown in this answer to a related question

Upvotes: 3

Trevor Merrifield
Trevor Merrifield

Reputation: 4691

It is simplest to use return values . If you want to eliminate boilerplate further you can use exceptions:

def Commands():
    command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
    if command != "Run" :
        raise StopIteration
if groups == 4 :
    try:
        while True:
            Commands()
    except StopIteration:
        print('Done')

Upvotes: 0

camstu
camstu

Reputation: 51

The variable restart isn't true when the function returns since it's out of scope. An easy solution may just be to have Commands() return a value true or false and have restart in the while loop assigned that value.

restart = Command() #Where command returns true or false

Short Description of the Scoping Rules?

Upvotes: 0

Related Questions