Перейти к содержимому

Syntaxerror return outside function python как исправить

  • автор:

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

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

Here’s what the error looks like:

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:

Exit fullscreen mode

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

syntaxerror ‘return’ outside function Python error [Causes & How to Fix]

In this Python tutorial, I will show you, how to fix, syntaxerror ‘return’ outside function python error with a few examples.

The ‘SyntaxError: ‘return’ outside function’ is quite common in Python, especially among beginners. This error is self-explanatory: it indicates that a ‘return’ statement has been used outside of a function. In this tutorial, we will deep dive into why this error occurs and provide methods to fix it.

Table of Contents

Understanding ‘return’ Statement in Python

To understand the error, it’s first essential to comprehend the role of the ‘return’ statement in Python. The ‘return’ statement is used in a function to end the execution of the function call and ‘returns’ the result (value) to the caller. The statements after the ‘return’ statement are not executed.

Here’s an example:

In this code, we have a function called ‘add_numbers’ that adds two numbers and uses the ‘return’ statement to send the result back to the caller.

What Causes ‘SyntaxError: ‘return’ Outside Function’ Error?

As the error message suggests, it occurs when the ‘return’ statement is used outside of a function. In Python, ‘return’ can only be used in the definition of a function. Using it elsewhere, like in loops, conditionals, or just on its own, is not allowed and will result in a SyntaxError.

Here is an example that will throw this error. Let’s say you have a list of grades and you want to calculate the average grade. You might write something like this:

f you run this script, it will throw a SyntaxError: ‘return’ outside function , because you’re using return in the main body of the script instead of within a function.

You can see the error message:

syntaxerror- 'return' outside function

How to Fix ‘SyntaxError: ‘return’ Outside Function’ Error?

The fix for this error is quite straightforward: ensure that the ‘return’ statement is used only inside function definitions.

In case you’re trying to use ‘return’ in your main script, consider whether you really want to return a value. If you’re attempting to output a value to the console, use the ‘print()’ function instead. If you’re trying to end the execution of your script, consider using ‘sys.exit()’.

Here’s how you can fix the error shown in the previous section:

In this corrected code, we’ve created a function named calculate_average that takes a list of grades, calculates the average, and then returns it. Now, the return statement is correctly placed inside a function, so there’s no SyntaxError . Finally, we call this function and print the returned value.

Conclusion

The ‘SyntaxError: ‘return’ outside function’ error in Python can be avoided by ensuring that ‘return’ statements are used appropriately within the body of function definitions only.

You may also like:

Fewlines4Biju Bijay

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

How to Solve Python SyntaxError: ‘return’ outside function

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?

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:

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,

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.

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.

Next, we will print the temperature_in_fahrenheit value to console

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

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:

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:

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

Python SyntaxError :'return' outside function

I would check my indentation, it looks off. Are you possibly mixing tabs and spaces? The PEP8 (Python Style Guide) recommends using 4 spaces only. Unlike other languages, whitepace makes a big difference in Python, so consistency is important.

The above also makes the following recommendation:

When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

In particular, your 2nd else seems to be off (probably should be indented), and this method def __div__(self, other): too (which I would think ought to be at the same level as your other def s — i.e., moved «out» rather than indented).

Problems mixing tabs/blanks are easy to have since both characters are «invisible».

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *