help icon indicating copy to clipboard operation
help copied to clipboard

SyntaxError: 'return' outside function

Open ghost opened this issue 6 years ago • 3 comments

I'm trying to use an if statement in my notebook but keep receiving the message?

SyntaxError: 'return' outside function

Even the simplest if statement receives that message, for example:

if 2==2:
    return 1

My indentation seems right, I don't know what's causing it.

ghost avatar Mar 04 '18 00:03 ghost

return statements must be inside functions, e.g.

def foo():
    if True:
        return 1

You can't have a return statement outside a function because without a function there isn't anything to return from.

minrk avatar Mar 04 '18 15:03 minrk

How can i return from the place where rhe number is called if it is wrong choice like this

[] Enter Your Choice: 1 [] Wrong Choice ! [*] Enter Your Choice:

Something like this

The-Albatros avatar Dec 01 '18 01:12 The-Albatros

You can use if statements to control when certain things happen. For input validation, you can use a while loop to wait for a valid input:

while True:
    choice = input('your choice: ')
    if choice == 1:
        # valid choice, stop asking!
        break
    else:
        print("invalid, try again!")

  

minrk avatar Dec 05 '18 11:12 minrk