1
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.

Miller
  • 23
  • 3
  • You can't have an `elif` without an `if`. Return `True` or `False` from your `commands()` function and use that to determine if you should restart or not. – khelwood Sep 04 '16 at 18:40
  • I have if elif and else, I removed them because they work fine and wanted to keep the code short and focus on the issue which lies with the restart and break not starting the outer 'while' loop – Miller Sep 04 '16 at 18:43

3 Answers3

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

Community
  • 1
  • 1
LinkBerest
  • 1,281
  • 3
  • 22
  • 30
0

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?

Community
  • 1
  • 1
camstu
  • 51
  • 1
  • 5
0

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')
Trevor Merrifield
  • 4,541
  • 2
  • 21
  • 24