Return outside of function syntax error

Hi guys I am trying to run this code, however I keep getting the return outside of function error, can anybody help with this?

import random

money = 100
num = random.randint(1, 10)


#Write your game of chance functions here
def coin_flip(guess, bet):
  coin_flip = random.choice(['Heads', 'Tails']) 
#randomly generates heads or tails choice.

if coin_flip == 'Heads':
    return "Congratulations, you guessed correctly! You have won " + str(money*2) +"!"

else:
  return "Unfortunately you have lost " + str(money/2) + " better luck next time"

#Call your game of chance functions here
print(coin_flip('Tails', 30))

And this syntax error keeps coming up:

File "script.py", line 9
    return "Congratulations, you guessed correctly! You have won " + str(money*2) +"!"
    ^
SyntaxError: 'return' outside function

Thanks in advance

What determines whether a line of code is inside a function in Python?

Whether it is in the function block?

How can you tell what is in a function block?

It is the code that is typedafter you creating the function, for example

def coin_flip(guess, bet):

and the code before you call the function:

print(coin_flip('Tails', 30))

Almost. It is the indented code on the lines following a :. When you create a function, the function declaration ends with :

def my_function(some_parameter):
    #indent either 2 or 4 spaces, and be consistent
    #every line with this same indentation is inside the function
    #until a line is reached that is out-dented to the same level
    #as the function declaration

#this line is not inside the function block

The same goes for if blocks and loops (while, for) and Class definitions. Lines of code intended to be in the same block must be indented the same.

In your code the if...else is not inside the function.

5 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.