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.

2
  • 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. Commented Sep 4, 2016 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 Commented Sep 4, 2016 at 18:43

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.