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

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

  • автор:

SyntaxError: ‘Return’ Outside Function in Python

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));
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.

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));
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.

Recommended Posts:

  • Python Online Compiler
  • Addition of two numbers in Python
  • Python Comment
  • Python Factorial
  • Python Continue Statement
  • Python map()
  • Polymorphism in Python
  • Python : end parameter in print()
  • Python eval
  • Install Opencv Python PIP Windows
  • Python Print Without Newline
  • Id() function in Python
  • Only Size-1 Arrays Can be Converted to Python Scalars
  • Area of Circle in Python
  • Bubble Sort in Python
  • Python slice() function
  • Convert List to String Python
  • indentationerror: unindent does not match any outer indentation level in Python
  • Python KeyError
  • Pangram Program in Python

В чем ошибка (пишет что return), но не могу понять где?

Vindicar

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

Ответ написан более года назад

Нравится 4 2 комментария

Denis @denislysenko Автор вопроса

так а что мне можно сделать, чтобы сделать return именно в этом месте?

if i in my_dict: my_dict[i] += 1 return True

Сергей Горностаев @sergey-gornostaev Куратор тега Python

denislysenko, ничего не сделать, это невозможно.

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:

def add_numbers(num1, num2): result = num1 + num2 return result print(add_numbers(5, 7)) # Outputs: 12

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:

grades = [85, 90, 78, 92, 88] total = sum(grades) average = total / len(grades) return average

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:

def calculate_average(grades): total = sum(grades) average = total / len(grades) return average grades = [85, 90, 78, 92, 88] print(calculate_average(grades)) # Outputs: 86.6

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:

  • invalid syntax error in Python
  • SyntaxError: Unexpected EOF while parsing
  • indexerror: string index out of range in Python
  • Python Return Function [6 use cases]

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.

SyntaxError: ‘return’ outside function

After you copy and paste your code into your post, you need to format it so we can see indentation, underscores, and other details. For instructions on formatting, see the link that looks like this:

Show formatting instructions ▼ 

Are you sure your indentation is correct? We cannot check it, because your code is not formatted, but your return statement needs to be indented by exactly one level, in order for it to be properly situated in the fizz_count function, without its being part of the for loop or the if block.

Here is the same code that you posted, but with correct indentation visible, so you can compare it to what you submitted to Codecademy’s Python interpreter:

def fizz_count(x): count = 0 for item in x: if item == 'fizz': count = count + 1 return count 

Each portion of the code is indented by one level to the right, with respect to its controlling header.

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

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