Меню

Return outside function python ошибка

Compiler showed:

File "temp.py", line 56
    return result
SyntaxError: 'return' outside function

Where was I wrong?

class Complex (object):
    def __init__(self, realPart, imagPart):
        self.realPart = realPart
        self.imagPart = imagPart            

    def __str__(self):
        if type(self.realPart) == int and type(self.imagPart) == int:
            if self.imagPart >=0:
                return '%d+%di'%(self.realPart, self.imagPart)
            elif self.imagPart <0:
                return '%d%di'%(self.realPart, self.imagPart)   
    else:
        if self.imagPart >=0:
                return '%f+%fi'%(self.realPart, self.imagPart)
            elif self.imagPart <0:
                return '%f%fi'%(self.realPart, self.imagPart)

        def __div__(self, other):
            r1 = self.realPart
            i1 = self.imagPart
            r2 = other.realPart
            i2 = other.imagPart
            resultR = float(float(r1*r2+i1*i2)/float(r2*r2+i2*i2))
            resultI = float(float(r2*i1-r1*i2)/float(r2*r2+i2*i2))
            result = Complex(resultR, resultI)
            return result

c1 = Complex(2,3)
c2 = Complex(1,4)
print c1/c2

What about this?

class Complex (object):
    def __init__(self, realPart, imagPart):
        self.realPart = realPart
        self.imagPart = imagPart            

    def __str__(self):
        if type(self.realPart) == int and type(self.imagPart) == int:
            if self.imagPart >=0:
                return '%d+%di'%(self.realPart, self.imagPart)
            elif self.imagPart <0:
                return '%d%di'%(self.realPart, self.imagPart)
        else:
            if self.imagPart >=0:
                return '%f+%fi'%(self.realPart, self.imagPart)
            elif self.imagPart <0:
                return '%f%fi'%(self.realPart, self.imagPart)

    def __div__(self, other):
        r1 = self.realPart
        i1 = self.imagPart
        r2 = other.realPart
        i2 = other.imagPart
        resultR = float(float(r1*r2+i1*i2)/float(r2*r2+i2*i2))
        resultI = float(float(r2*i1-r1*i2)/float(r2*r2+i2*i2))
        result = Complex(resultR, resultI)
        return result

c1 = Complex(2,3)
c2 = Complex(1,4)
print c1/c2

Syntaxerror: ‘return’ outside function

This syntax error is nothing but a simple indentation error, generally, this error occurs when the indent or return function does not match or align to the indent of the defined function.

Example

# Python 3 Code

def myfunction(a, b):
  # Print the value of a+b
  add = a + b
return(add)

# Print values in list
print('Addition: ', myfunction(10, 34));

Output

File "t.py", line 7
    return(add)
    ^
SyntaxError: 'return' outside function

As you can see that line no. 7 is not indented or align with myfunction(), due to this python compiler compile the code till line no.6 and throws the error ‘return statement is outside the function.

Syntaxerror: 'return' outside function

Correct Example

# Python 3 Code

def myfunction(a, b):
  # Print the value of a+b
  add = a + b

  return(add)

# Print values in list
print('Addition: ', myfunction(10, 34));

Output

Addition:  44

Conclusion

We have understood that indentation is extremely important in programming. As Python does not use curly braces like C, indentation and whitespaces are crucial. So, when you type in the return statement within the function the result is different than when the return statement is mentioned outside. It is best to check your indentation properly before executing a function to avoid any syntax errors.   

When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

I get the following error

SyntaxError: 'return' outside function

I’ve carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

asked Oct 20, 2011 at 20:54

Jeff's user avatar

3

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

answered Oct 20, 2011 at 21:05

Raymond Hettinger's user avatar

Raymond HettingerRaymond Hettinger

211k62 gold badges373 silver badges473 bronze badges

5

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Antonio's user avatar

Antonio

18.9k12 gold badges95 silver badges194 bronze badges

answered Feb 9, 2014 at 2:09

buzzard51's user avatar

buzzard51buzzard51

1,3422 gold badges21 silver badges40 bronze badges

1

To break a loop, use break instead of return.

Or put the loop or control construct into a function, only functions can return values.

answered Oct 20, 2011 at 21:45

Jürgen Strobel's user avatar

0

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

answered Mar 28, 2017 at 22:13

Eugene Yarmash's user avatar

Eugene YarmashEugene Yarmash

138k39 gold badges318 silver badges372 bronze badges

When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

I get the following error

SyntaxError: 'return' outside function

I’ve carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

asked Oct 20, 2011 at 20:54

Jeff's user avatar

3

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

answered Oct 20, 2011 at 21:05

Raymond Hettinger's user avatar

Raymond HettingerRaymond Hettinger

211k62 gold badges373 silver badges473 bronze badges

5

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Antonio's user avatar

Antonio

18.9k12 gold badges95 silver badges194 bronze badges

answered Feb 9, 2014 at 2:09

buzzard51's user avatar

buzzard51buzzard51

1,3422 gold badges21 silver badges40 bronze badges

1

To break a loop, use break instead of return.

Or put the loop or control construct into a function, only functions can return values.

answered Oct 20, 2011 at 21:45

Jürgen Strobel's user avatar

0

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

answered Mar 28, 2017 at 22:13

Eugene Yarmash's user avatar

Eugene YarmashEugene Yarmash

138k39 gold badges318 silver badges372 bronze badges

Python & Machine Learning training courses

In this Python tutorial, we will discuss how to fix an error, syntaxerror return outside function python, and can’t assign to function call in python The error return outside function python comes while working with function in python.

In python, this error can come when the indentation or return function does not match.

Example:

def add(x, y):
  sum = x + y
return(sum)
print(" Total is: ", add(20, 50))

After writing the above code (syntaxerror return outside function python), Ones you will print then the error will appear as a “ SyntaxError return outside function python ”. Here, line no 3 is not indented or align due to which it throws an error ‘return’ outside the function.

You can refer to the below screenshot python syntaxerror: ‘return’ outside function

Syntaxerror return outside function python
python syntaxerror: ‘return’ outside function

To solve this SyntaxError: return outside function python we need to check the code whether the indentation is correct or not and also the return statement should be inside the function so that this error can be resolved.

Example:

def add(x, y):
  sum = x + y
  return(sum)
print(" Total is: ", add(20, 50))

After writing the above code (syntaxerror return outside function python), Once you will print then the output will appear as a “ Total is: 70 ”. Here, line no. 3 is resolved by giving the correct indentation of the return statement which should be inside the function so, in this way we can solve this syntax error.

You can refer to the below screenshot:

Syntaxerror return outside function python
return outside function python

SyntaxError can’t assign to function call in python

In python, syntaxerror: can’t assign to function call error occurs if you try to assign a value to a function call. This means that we are trying to assign a value to a function.

Example:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
sold_1000_times(chocolate) = top_sellers
print(top_sellers)

After writing the above code (syntaxerror: can’t assign to function call in python), Ones you will print “top_sellers” then the error will appear as a “ SyntaxError: cannot assign to function call ”. Here, we get the error because we’re trying to assign a value to a function call.

You can refer to the below screenshot cannot assign to function call in python

SyntaxError can't assign to function call in python
SyntaxError can’t assign to function call in python

To solve this syntaxerror: can’t assign to function call we have to assign a function call to a variable. We have to declare the variable first followed by an equals sign, followed by the value that should be assigned to that variable. So, we reversed the order of our variable declaration.

Example:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
top_sellers
 = sold_1000_times(chocolate)
print(top_sellers)

After writing the above code (cannot assign to function call in python), Ones you will print then the output will appear as “[{ “name”: “Kit Kat”, “sold”: 1200}, {“name”: “Dairy Milk Silk”, “sold”: 1208}] ”. Here, the error is resolved by giving the variable name first followed by the value that should be assigned to that variable.

You can refer to the below screenshot cannot assign to function call in python is resolved

SyntaxError can't assign to function call in python
SyntaxError can’t assign to function call in python

You may like the following Python tutorials:

  • Remove character from string Python
  • Create an empty array in Python
  • Invalid syntax in python
  • syntaxerror invalid character in identifier python3
  • How to handle indexerror: string index out of range in Python
  • Unexpected EOF while parsing Python
  • Python built-in functions with examples

This is how to solve python SyntaxError: return outside function error and SyntaxError can’t assign to function call in python. This post will be helpful for the below error messages:

  • syntaxerror return outside function
  • python syntaxerror: ‘return’ outside function
  • return outside of function python
  • return’ outside function python
  • python error return outside function
  • python ‘return’ outside function
  • syntaxerror return not in function

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Image of Return Outside Function error in Python

Table of Contents

  • Introduction
  • The Return Statement
  • Return Outside Function Python SyntaxError
  • Return Outside Function Python SyntaxError due to Indentation
  • Return Outside Function Python SyntaxError due to Looping
  • Summary
  • Next Steps

Introduction

Functions are an extremely useful tool when it comes to programming. They allow you to wrap a block of code into one neat package and give it a name. Then, you can call that block from other places in the code, and perform the defined task as many times as you’d like.

What’s more, functions allow you to return the result of some computation back to the main Python program. However, you need to be careful how you do this; otherwise, you might get an error.

The Python language can throw a variety of errors and exceptions, such as AttributeError, TypeError, and SyntaxError.

In this article, you’ll take a closer look at the return statement and how to fix the return outside function Python error, which you may have encountered as:

SyntaxError: ‘return’ outside function

The Return Statement

The return statement is used to end a function’s execution and pass a value back to where a function was called. For example:

def return_variable():
    a = 1
    return a

You define a function called return_variable() that assigns the value 1 to the variable a. Then, it returns that value, passing it back to the main Python program for further processing.

If you run this code in the interpreter, then calling the function name will immediately display the result of the return statement:

>>> def return_variable():
...     a = 1
...     return a
...
>>> return_variable()
1

The function call runs the code inside the function block. Then, the function sends the result of a back to the interpreter.

If you instead defined this function in a file, then you could use the print statement to show the result instead:

# return_variable.py

def return_variable():
    a = 1
    return a

print(return_variable())

Now, the return statement sends the result back to the main Python program that’s running. Here, it’s the file return_variable.py. In other words, you can now use the result of that return statement anywhere else in the file — for instance, in the print statement at the end. When you run this file from the terminal, the result will be displayed:

$ python3 return_variable.py
1

Another common technique is to assign the result of the function to a variable:

# return_variable_2.py

def return_variable():
    a = 1
    return a

b = return_variable()
print(b)

No matter where you define the function, the return statement will allow you to work with the result of a function.

Return Outside Function Python SyntaxError

If the return statement is not used properly, then Python will raise a SyntaxError alerting you to the issue. In some cases, the syntax error will say ’return’ outside function. To put it simply, this means that you tried to declare a return statement outside the scope of a function block.

The return statement is inextricably linked to function definition. In the next few sections, you’ll take a look at some improper uses of the return statement, and how to fix them.

Return Outside Function Python SyntaxError due to Indentation

Often, when one is confronted with a return outside function Python SyntaxError, it’s due to improper indentation. Indentation tells Python that a series of statements and operations belong to the same block or scope. When you place a return statement at the wrong level of indentation, Python won’t know which function to associate it with.

Let’s look at an example:

>>> def add(a, b):
...     c = a + b
... return c
  File "<stdin>", line 3
    return c
    ^
SyntaxError: invalid syntax

Here, you try to define a function to add two variables, a and b. You set the value of c equal to the sum of the others, and then you want to return this value.

However, after you enter return c, Python raises a syntax error. Notice the caret symbol ^ pointing to the location of the issue. There’s something wrong with the return statement, though the interpreter doesn’t say exactly what.

If you place the function in a file and run it from the terminal, then you’ll see a bit more information:

$ python3 bad_indentation.py
  File "bad_indentation.py", line 5
    return c
    ^
SyntaxError: 'return' outside function

Now you can see Python explicitly say that there’s a return statement declared outside of a function.

Let’s take a closer look at the function you defined:

The red line shows the indentation level where the function definition starts. Anything that you want to be defined as a part of this function should be indented four spaces in the lines that follow. The first line, c = a + b, is properly indented four spaces over, so Python includes it in the function block.

The return statement, however, is not indented at all. In fact, it’s at the same level as the def keyword. Since it’s not indented, Python doesn’t include it as part of the function block. However, all return statements must be part of a function block — and since this one doesn’t match the indentation level of the function scope, Python raises the error.

This problem has a simple solution, and that’s to indent the return statement the appropriate number of spaces:

Now, the return statement doesn’t break the red line. It’s been moved over four spaces to be included inside the function block. When you run this code from a file or in the interpreter, you get the correct result:

>>> def add(a, b):
...     c = a + b
...     return c
...
>>> add(2, 3)
5

Return Outside Function Python SyntaxError due to Looping

Another place where one might encounter this error is within a loop body. Loops are a way for the programmer to execute the same block of code as many times as needed, without having to write the block of statements explicitly each time.

The way a loop is defined may look similar to how a function is defined. Because of this, some programmers may confuse the syntax between the two. For instance, here’s an attempt to return a value from a while loop:

>>> count = 0
>>> while count < 10:
...     print(count)
...     if count == 7:
...         return count
...     count += 1
...
  File "<stdin>", line 4
SyntaxError: 'return' outside function

This code block starts a count at zero and defines a while loop. As long as count is less than ten, then the loop will print its current value. However, when count reaches 7, then the loop should stop and return its value to the main program.

You can clearly see that the interpreter raises a return outside function Python syntax error here as well. The interpreter points out the location of the error: it’s in line 4, the fourth line of the while loop body, which says return count.

This raises an error because return statements can only be placed inside function definitions. You cannot return a value from a standalone loop. There are two solutions to this sort of problem. One is to replace return with a break statement, which will exit the loop at the specified condition:

>>> count = 0
>>> while count < 10:
...     print(count)
...     if count == 7:
...         break
...     count += 1
...
0
1
2
3
4
5
6
7
>>> count
7

Now, the fourth line of the loop body says break instead of return count. You can see that the loop executes with no errors, printing the value of count and incrementing it by one on each iteration. When it reaches 7, the loop breaks. Since you update the value on each iteration, the value is still stored when the loop breaks, and you can print it out to see that it is equal to 7.

However, there is a way to use a return statement with loops. All you have to do is wrap the loop in a function definition. Then, you can keep the return count without any syntax errors.

Wrap the while loop in a function and save the file as return_while.py:

# return_while.py

def counter():
    count = 0
        while count < 10:
        print(count)
        if count == 7:
            return count
        count += 1

counter()

The while loop still has a return statement in it, but since the entire loop body is included in counter(), Python correctly associates this with the function definition. When you run this code in the terminal, the function will run without issue:

$ python3 return_while.py
0
1
2
3
4
5
6
7

To see the return statement in action, modify the file return_while.py to store the result of the function call and then print it out:

# return_while.py

def counter():
    count = 0
        while count < 10:
        print(count)
        if count == 7:
            return count
        count += 1

result = counter()
print("The result is: ", result)

Now, when you run this file in the terminal again, the output will more clearly show you the result returned from the function call:

$ python3 return_while.py
0
1
2
3
4
5
6
7
The result is: 7

Summary

In this article, you learned how to fix the return outside function Python syntax error.

You reviewed how the return statement works in Python, then took a look at two common instances where you might see this error raised. Now, you know to check for proper indentation when using return statements and what to do when you want to include them in a loop body.

Next Steps

Functions are an essential part of programming, and when you learn how to write your own, you can really take your code to the next level. If you need a refresher, then our tutorial on functions in Python 3 is a great place to get started.

You don’t have to define your own functions for everything, though. The Python standard library comes equipped with dozens you can use straight out of the box, like min() and floor().

If you’re interested in learning more about the basics of Python, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you’ll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes

blog banner for post titled: How to Solve Python SyntaxError: ‘return’ outside function

In Python, the return keyword ends the execution flow of a function and sends the result value to the main program. You must define the return statement inside the function where the code block ends. If you define the return statement outside the function block, you will raise the error “SyntaxError: ‘return’ outside function”.

This tutorial will go through the error in more detail, and we will go through an example scenario to solve it.

Table of contents

  • SyntaxError: ‘return’ outside function
    • What is a Syntax Error in Python?
    • What is a Return Statement?
  • Example: Return Statement Outside of Function
    • Solution
  • Summary

SyntaxError: ‘return’ outside function

What is a Syntax Error in Python?

Syntax refers to the arrangement of letters and symbols in code. A Syntax error means you have misplaced a symbol or a letter somewhere in the code. Let’s look at an example of a syntax error:

number = 45

print()number
    print()number
           ^
SyntaxError: invalid syntax

The ^ indicates the precise source of the error. In this case, we have put the number variable outside of the parentheses for the print function,

print(number)
45

The number needs to be inside parentheses to print correctly.

What is a Return Statement?

We use a return statement to end the execution of a function call and return the value of the expression following the return keyword to the caller. It is the final line of code in our function. If you do not specify an expression following return, the function will return None. You cannot use return statements outside the function you want to call. Similar to the return statement, the break statement cannot be outside of a loop. If you put a break statement outside of a loop you will raise “SyntaxError: ‘break’ outside loop“. Let’s look at an example of incorrect use of the return statement.

Example: Return Statement Outside of Function

We will write a program that converts a temperature from Celsius to Fahrenheit and returns these values to us. To start, let’s define a function that does the temperature conversion.

# Function to convert temperature from Celsius to Fahrenheit

def temp_converter(temp_c):

    temp_f = (temp_c * 9 / 5) + 32

return temp_f

The function uses the Celsius to Fahrenheit conversion formula and returns the value. Now that we have written the function we can call it in the main program. We can use the input() function to ask the user to give us temperature data in Celsius.

temperature_in_celsius = float(input("Enter temperature in Celsius"))

temperature_in_fahrenheit = temp_converter(temperature_in_celsius)

Next, we will print the temperature_in_fahrenheit value to console

print(<meta charset="utf-8">temperature_in_fahrenheit)

Let’s see what happens when we try to run the code:

    return temp_f
    ^
SyntaxError: 'return' outside function

The code failed because we have specified a return statement outside of the function temp_converter.

Solution

To solve this error, we have to indent our return statement so that it is within the function. If we do not use the correct indentation, the Python interpreter will see the return statement outside the function. Let’s see the change in the revised code:

# Function to convert temperature from Celsius to Fahrenheit

def temp_converter(temp_c):

    temp_f = (temp_c * 9 / 5) + 32

    return temp_f
temperature_in_celsius = float(input("Enter temperature in Celsius"))

temperature_in_fahrenheit = temp_converter(temperature_in_celsius)

print(temperature_in_fahrenheit)
Enter temperature in Celsius10

50.0

The program successfully converts 10 degrees Celsius to 50 degrees Fahrenheit.

For further reading on using indentation correctly in Python, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level.

Summary

Congratulations on reading to the end of this tutorial! The error: “SyntaxError: ‘return’ outside function” occurs when you specify a return statement outside of a function. To solve this error, ensure all of your return statements are indented to appear inside the function as the last line instead of outside of the function.

Here is some other SyntaxErrors that you may encounter:

  • SyntaxError: unexpected character after line continuation character
  • SyntaxError: can’t assign to function call

Go to the online courses page on Python to learn more about Python for data science and machine learning.

A return statement sends a value from a function to a main program. If you specify a return statement outside of a function, you’ll encounter the “SyntaxError: ‘return’ outside function” error.

In this guide, we explore what the “‘return’ outside function” error means and why it is raised. We’ll walk through an example of this error so you can figure out how to solve it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

SyntaxError: ‘return’ outside function

Return statements can only be included in a function. This is because return statements send values from a function to a main program. Without a function from which to send values, a return statement would have no clear purpose.

Return statements come at the end of a block of code in a function. Consider the following example:

def add_two_numbers(x, y):
	answer = x + y
	return answer

Our return statement is the final line of code in our function. A return statement may be used in an if statement to specify multiple potential values that a function could return.

An Example Scenario

We’re going to write a program that calculates whether a student has passed or failed a computing test. To start, let’s define a function that checks whether a student has passed or failed. The pass-fail boundary for the test is 50 marks.

def check_if_passed(grade):
	if grade > 50:
		print("Checked")
		return True
	else: 
		print("Checked")
return False

Our function can return two values: True or False. If a student’s grade is over 50 (above the pass-fail boundary), the value True is returned to our program. Otherwise, the value False is returned. Our program prints the value “Checked” no matter what the outcome of our if statement is so that we can be sure a grade has been checked.

Now that we have written this function, we can call it in our main program. First, we need to ask the user for the name of the student whose grade the program should check, and for the grade that student earned. We can do this using an input() statement:

name = input("Enter the student's name: ")
grade = int(input("Enter the student's grade: "))

The value of “grade” is converted to an integer so we can compare it with the value 50 in our function. Let’s call our function to check if a student has passed their computing test:

has_passed = check_if_passed(grade)
if has_passed == True:
	print("{} passed their test with a grade of {}.".format(name, grade))
else:
	print("{} failed their test with a grade of {}.".format(name, grade))

We call the check_if_passed() function to determine whether a student has passed their test. If the student passed their test, a message is printed to the console telling us they passed; otherwise, we are informed the student failed their test.

Let’s run our code to see if it works:

  File "test.py", line 6
	return False
	^
SyntaxError: 'return' outside function

An error is returned.

The Solution

We have specified a return statement outside of a function. Let’s go back to our check_if_passed() function. If we look at the last line of code, we can see that our last return statement is not properly indented.

…
	else: 
		print("Checked")
return False

The statement that returns False appears after our function, rather than at the end of our function. We can fix this error by intending our return statement to the correct level:

	else: 
		print("Checked")
return False

The return statement is now part of our function. It will return the value False if a student’s grade is not over 50. Let’s run our program again:

Enter the student's name: Lisa
Enter the student's grade: 84
Checked
Lisa passed their test with a grade of 84.

Our program successfully calculates that a student passed their test.

Conclusion

The “SyntaxError: ‘return’ outside function” error is raised when you specify a return statement outside of a function. To solve this error, make sure all of your return statements are properly indented and appear inside a function instead of after a function.

Now you have the knowledge you need to fix this error like an expert Python programmer!

The

return

keyword in Python is used to end the execution flow of the function and send the result value to the main program. The return statement must be defined inside the function when the function is supposed to end. But if we define a return statement outside the function block, we get the

SyntaxError: 'return' outside function

Error.

In this Python guide, we will explore this Python error and discuss how to solve it. We will also see an example scenario where many Python learners commit this mistake, so you could better understand this error and how to debug it. So let’s get started with the Error Statement.

The Error Statement

SyntaxError: 'return' outside function

is divided into two parts. The first part is the Python Exception

SyntaxError

, and the second part is the actual Error message

'return' outside function

.



  1. SyntaxError

    :

    SyntaxError occurs in Python when we write a Python code with invalid syntax. This Error is generally raised when we make some typos while writing the Python program.


  2. 'return' outside function

    :

    This is the Error Message, which tells us that we are using the

    return

    keyword outside the function body.


Error Reason

The  Python

return

is a reserved keyword used inside the function body when a function is supposed to return a value. The return value can be accessed in the main program when we call the function. The

return

keyword is exclusive to Python functions and can only be used inside the function’s local scope. But if we made a typo by defining a return statement outside the function block, we will encounter the «SyntaxError: ‘return’ outside function» Error.


For example

Let’s try to define a return statement outside the function body, and see what we get as an output.

# define a function
def add(a,b):
    result = a+b

# using return out of the function block(error)
return result

a= 20
b= 30
result = add(a,b) 
print(f"{a}+{b} = {result}")


Output

 File "main.py", line 6
return result
^
SyntaxError: 'return' outside function


Break the code

We are getting the «SyntaxError: ‘return’ outside function» Error as an output. This is because, in line 6, we are using the

return result

statement outside the function, which is totally invalid in Python. In Python, we are supposed to use the return statement inside the function, and if we use it outside the function body, we get the SyntaxError, as we are encountering in the above example. To solve the above program, we need to put the return statement inside the function block.


solution

# define a function
def add(a,b):
    result = a+b
    # using return inside the function block
    return result

a= 20
b= 30

result = add(a,b)
print(f"{a}+{b} = {result}")


Common Scenario

The most common scenario where many Python learners encounter this error is when they forget to put the indentation space for the

return

statement and write it outside the function. To write the function body code, we use indentation and ensure that all the function body code is intended. The

return

statement is also a part of the function body, and it also needs to be indented inside the function block.

In most cases, the

return

statement is also the last line for the function, and the coder commits the mistake and writes it in a new line without any indentation and encounters the SyntaxError.


For example

Let’s write a Python function

is_adult()

that accept the

age

value as a parameter and return a boolean value

True

if the age value is equal to or greater than 18 else, it returns False. And we will write the

return

Statements outside the function block to encounter the error.

# define the age
age = 22

def is_adult(age):
    if age >= 18:
        result = True
    else:
        result = False
return result  #outside the function

result = is_adult(age)

print(result)


Output

 File "main.py", line 9
return result #outside the function
^
SyntaxError: 'return' outside function


Break The code

The error output reason for the above code is pretty obvious. If we look at the output error statement, we can clearly tell that the

return result

statement is causing the error because it is defined outside the

is_adult()

function.


Solution

To solve the above problem, all we need to do is put the return statement inside the

is_adult()

function block using the indentation.


Example Solution

# define the age
age = 22

def is_adult(age):
    if age >= 18:
        result = True
    else:
        result = False
    return result  #inside the function

result = is_adult(age)

print(result)


Output

True


Final Thoughts!

The Python

'return' outside function

is a common Python SyntaxError. It is very easy to find and debug this error. In this Python tutorial, we discussed why this error occurs in Python and how to solve it. We also discussed a common scenario when many python learners commit this error.

You can commit many typos in Python to encounter the SyntaxError, and the ‘return’ outside the Function message will only occur when you define a return statement outside the function body. If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • What is Python used for?

  • Python TypeError: ‘float’ object cannot be interpreted as an integer Solution

  • How to run a python script?

  • Python TypeError: ‘NoneType’ object is not callable Solution

  • Python Features

  • How to Play sounds in Python?

  • Python Interview Questions

  • Python typeerror: list indices must be integers or slices, not str Solution

  • Best Python IDEs

  • Read File in Python

Denis

@denislysenko

data engineer

array = [1,2,5,8,1]

my_dict = {}
for i in array:
    if i in my_dict:
        my_dict[i] += 1
        return True
    else:
        my_dict[i] = 1 
        
    return False
    

#ошибка
  File "main.py", line 8
    return True
    ^
SyntaxError: 'return' outside function

Спасибо!


  • Вопрос задан

    07 апр. 2022

  • 246 просмотров

Ну тебе же английским по белому написано: ‘return’ outside function
Оператор return имеет смысл только в теле функции, а у тебя никакого объявления функции нет.

‘return’ outside function

Пригласить эксперта


  • Показать ещё
    Загружается…

31 янв. 2023, в 07:51

50000 руб./за проект

31 янв. 2023, в 07:34

4500 руб./за проект

31 янв. 2023, в 04:30

200 руб./за проект

Минуточку внимания

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Return code 1612 hp ошибка
  • Return code 1603 hp ошибка