В этом руководстве по Python я покажу вам, как исправить, синтаксическая ошибка ‘возврат’ вне функции python ошибка с несколькими примерами.
«SyntaxError: «возврат» внешней функции» довольно распространен в Python, особенно среди новичков. Эта ошибка говорит сама за себя: она указывает на то, что оператор «return» использовался вне функции. В этом руководстве мы подробно рассмотрим, почему возникает эта ошибка, и предложим способы ее исправления.
Чтобы понять ошибку, сначала необходимо понять роль оператора «return» в Python. Оператор «return» используется в функции для завершения выполнения вызова функции и «возвращает» результат (значение) вызывающей стороне. Операторы после оператора return не выполняются.
Вот пример:
def add_numbers(num1, num2):
result = num1 + num2
return result
print(add_numbers(5, 7)) # Outputs: 12
В этом коде у нас есть функция add_numbers, которая складывает два числа и использует оператор return для отправки результата обратно вызывающей стороне.
Что вызывает ошибку «SyntaxError: ‘return’ Outside Function’?
Как следует из сообщения об ошибке, это происходит, когда оператор return используется вне функции. В Python return можно использовать только в определении функции. Использование его в другом месте, например, в циклах, условных выражениях или просто само по себе, не допускается и приведет к ошибке SyntaxError.
Вот пример, который выдаст эту ошибку. Допустим, у вас есть список оценок, и вы хотите рассчитать среднюю оценку. Вы можете написать что-то вроде этого:
grades = [85, 90, 78, 92, 88]
total = sum(grades)
average = total / len(grades)
return average
Если вы запустите этот скрипт, он выдаст SyntaxError: 'return' outside function
потому что вы используете return
в основной части скрипта, а не внутри функции.
Вы можете увидеть сообщение об ошибке:
Как исправить ошибку «SyntaxError: ‘return’ Outside Function»?
Исправление этой ошибки довольно простое: убедитесь, что оператор «return» используется только внутри определений функций.
Если вы пытаетесь использовать return в своем основном скрипте, подумайте, действительно ли вы хотите вернуть значение. Если вы пытаетесь вывести значение на консоль, используйте вместо этого функцию print(). Если вы пытаетесь завершить выполнение своего скрипта, рассмотрите возможность использования «sys.exit()».
Вот как вы можете исправить ошибку, показанную в предыдущем разделе:
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
В этом исправленном коде мы создали функцию с именем calculate_average
который берет список оценок, вычисляет среднее значение, а затем возвращает его. Сейчас return
оператор правильно размещен внутри функции, поэтому нет SyntaxError
. Наконец, мы вызываем эту функцию и печатаем возвращаемое значение.
Заключение
‘SyntaxError: ‘возврат’ вне функции’ ошибок в Python можно избежать, обеспечив правильное использование операторов return только в теле определений функций.
Вам также может понравиться:
Я Биджай Кумар, Microsoft MVP в SharePoint. Помимо SharePoint, последние 5 лет я начал работать над Python, машинным обучением и искусственным интеллектом. За это время я приобрел опыт работы с различными библиотеками Python, такими как Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn и т. д. для различных клиентов в США, Канаде, Великобритании, Австралии, Новая Зеландия и т. д. Проверьте мой профиль.
Ссылка на источник
@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
Спасибо!
-
Вопрос задан
-
1808 просмотров
Ну тебе же английским по белому написано: ‘return’ outside function
Оператор return имеет смысл только в теле функции, а у тебя никакого объявления функции нет.
‘return’ outside function
Пригласить эксперта
-
Показать ещё
Загружается…
21 сент. 2023, в 19:28
10000 руб./за проект
21 сент. 2023, в 19:06
11111 руб./за проект
21 сент. 2023, в 19:00
6000000 руб./за проект
Минуточку внимания
The “SyntaxError: return outside function” error occurs when you try to use the return
statement outside of a function in Python. This error is usually caused by a mistake in your code, such as a missing or misplaced function definition or incorrect indentation on the line containing the return
statement.
In this tutorial, we will look at the scenarios in which you may encounter the SyntaxError: return outside function
error and the possible ways to fix it.
What is the return statement?
A return
statement is used to exit a function and return a value to the caller. It can be used with or without a value. Here’s an example:
# function that returns if a number is even or not def is_even(n): return n % 2 == 0 # call the function res = is_even(6) # display the result print(res)
Output:
True
In the above example, we created a function called is_even()
that takes a number as an argument and returns True
if the number is even and False
if the number is odd. We then call the function to check if 6 is odd or even. We then print the returned value.
Why does the SyntaxError: return outside function
occur?
The error message is very helpful here in understanding the error. This error occurs when the return statement is placed outside a function. As mentioned above, we use a return
statement to exit a function. Now, if you use a return
statement outside a function, you may encounter this error.
The following are two common scenarios where you may encounter this error.
1. Check for missing or misplaced function definitions
The most common cause of the “SyntaxError: return outside function” error is a missing or misplaced function definition. Make sure that all of your return
statements are inside a function definition.
For example, consider the following code:
print("Hello, world!") return 0
Output:
Hello, world! Cell In[50], line 2 return 0 ^ SyntaxError: 'return' outside function
This code will produce the “SyntaxError: return outside function” error because the return
statement is not inside a function definition.
To fix this error, you need to define a function and put the return
statement inside it. Here’s an example:
def say_hello(): print("Hello, world!") return 0 say_hello()
Output:
Hello, world! 0
Note that here we placed the return
statement inside the function say_hello()
. Note that it is not necessary for a function to have a return
statement but if you have a return
statement, it must be inside a function enclosure.
2. Check for indentation errors
Another common cause of the “SyntaxError: return outside function” error is an indentation error. In Python, indentation is used to indicate the scope of a block of code, such as a function definition.
Make sure that all of your return
statements are indented correctly and are inside the correct block of code.
For example, consider the following code:
def say_hello(): print("Hello, world!") return 0 say_hello()
Output:
Cell In[52], line 3 return 0 ^ SyntaxError: 'return' outside function
In the above example, we do have a function and a return statement but the return statement is not enclosed insdie the function’s scope. To fix the above error, indent the return
statement such that it’s correctly inside the say_hello()
function.
def say_hello(): print("Hello, world!") return 0 say_hello()
Output:
Hello, world! 0
Conclusion
The “SyntaxError: return outside function” error is a common error in Python that is usually caused by a missing or misplaced function definition or an indentation error. By following the steps outlined in this tutorial, you should be able to fix this error and get your code running smoothly.
You might also be interested in –
- How to Fix – SyntaxError: EOL while scanning string literal
- How to Fix – IndexError: pop from empty list
-
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts
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
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
.
-
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. -
'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