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): s...

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

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.

Cover image for [Solved] SyntaxError: ‘return’ outside function in Python

Reza Lavarian

🚫 SyntaxError: ‘return’ outside function

This post was originally published on decodingweb.dev as part of the Python Syntax Errors series.

Python raises the error “SyntaxError: ‘return’ outside function” once it encounters a return statement outside a function.

Here’s what the error looks like:

File /dwd/sandbox/test.py, line 4
  return True
  ^^^^^^^^^^^
SyntaxError: 'return' outside function

Enter fullscreen mode

Exit fullscreen mode

Based on Python’s syntax & semantics a return statement may only be used in a function — to return a value to the caller.

However, if — for some reason — a return statement isn’t nested in a function, Python’s interpreter raises the «SyntaxError: ‘return’ outside function» error.

Using the return statement outside a function isn’t something you’d do on purpose, though; This error usually happens when the indentation-level of a return statement isn’t consistent with the rest of the function.

Additionally, it can occur when you accidentally use a return statement to break out of a loop (rather than using the break statement)

How to fix SyntaxError: ‘return’ outside function

This SyntaxError happens under various scenarios:

1. Inconsistent indentation
2. Using the return statement to break out of a loop
3. Let’s explore each scenario with some examples.

1. Inconsistent indentation: A common cause of this syntax error is an inconsistent indentation, meaning Python doesn’t consider the return statement a part of a function because its indentation level is different.

In the following example, we have a function that accepts a number and checks if it’s an even number:

def isEven(value):
  remainder = value % 2

  # if the remainder of the division is zero, it's even
return remainder == 0

Enter fullscreen mode

Exit fullscreen mode

As you probably noticed, we hadn’t indented the return statement relative to the isEven() function.

To fix it, we correct the indentation like so:

# ✅ Correct
def isEven(value):
  remainder = value % 2

  # if the remainder of the division is zero, it's even
  return remainder == 0

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Let’s see another example:

def check_age(age):
  print('checking the rating...')

# if the user is under 12, don't play the movie
if (age < 12):
  print('The movie can't be played!')
  return

Enter fullscreen mode

Exit fullscreen mode

In the above code, the if block has the same indentation level as the top-level code. As a result, the return statement is considered outside the function.

To fix the error, we bring the whole if block to the same indentation level as the function.

# ✅ Correct
def check_age(age):
  print('checking the rating...')

  # if the user is under 12, don't play the movie
  if (age < 12):
    print('The movie can't be played!')
    return

  print('Playing the movie')

check_age(25)
# output: Playing the movie

Enter fullscreen mode

Exit fullscreen mode

Using the return statement to break out of a loop: Another reason for this error is using a return statement to stop a for loop located in the top-level code.

The following code is supposed to print the first fifteen items of a range object:

items = range(1, 100)

# print the first 15 items
for i in items:
  if i > 15:
    return
  print(i)

Enter fullscreen mode

Exit fullscreen mode

However, based on Python’s semantics, the return statement isn’t used to break out of functions — You should use the break statement instead:

# ✅ Correct
items = range(1, 100)

# print the first 15 items
for i in items:
  if i > 15:
    break
  print(i)

Enter fullscreen mode

Exit fullscreen mode

And that’s how you’d fix the error «SyntaxError: ‘return’ outside function» in Python.

In conclusion, always make sure the return statement is indented relative to its surrounding function. Or if you’re using it to break out of a loop, replace it with a break statement.

Alright, I think it does it. I hope this quick guide helped you solve your problem.

Thanks for reading.

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 badges475 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 badges475 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

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!

Понравилась статья? Поделить с друзьями:
  • Return code 1612 hp ошибка
  • Retry was not successful ошибка
  • Retry timeout exceeded ошибка
  • Retry failed reason power calibration area error
  • Retrofit2 httpexception http 500 internal server error