У вас вообще беда с пробелами из-за этого Ваша функция birthday()
принимает на вход amount
и iteration
, не возвращает ничего, а только импортирует from random import randrange
. Если Вы хотите, чтобы весь код, кроме вывода результата, был в теле функции это должно выглядеть так:
def birthday(amount, iteration=10000):
from random import randrange
matches = 0
for x in range(iteration):
birthdays = []
for y in range(1, amount + 1):
birthdays.append(randrange(1, 366))
tmp = set(birthdays)
if len(tmp) != len(birthdays):
matches += 1
return matches / iteration * 100
result = birthday(23)
print(result)
@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
Спасибо!
-
Вопрос заданболее года назад
-
1303 просмотра
Ну тебе же английским по белому написано: ‘return’ outside function
Оператор return имеет смысл только в теле функции, а у тебя никакого объявления функции нет.
‘return’ outside function
Пригласить эксперта
-
Показать ещё
Загружается…
04 июн. 2023, в 01:35
1500 руб./за проект
04 июн. 2023, в 01:25
40000 руб./за проект
03 июн. 2023, в 23:42
1500 руб./за проект
Минуточку внимания
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
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 the «‘return’ outside function» error?
This syntax error happens under various scenarios including:
- Inconsistent indentation
- Using the return statement to break out of a loop
Let’s explore each scenario with some examples.
👇 Continue Reading
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:
# 🚫 SyntaxError: 'return' outside function
def isEven(value):
remainder = value % 2
# if the remainder of the division is zero, it's even
return remainder == 0
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
Problem solved!
Let’s see another example:
# 🚫 SyntaxError: 'return' outside function
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
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
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:
# 🚫 SyntaxError: 'return' outside function
items = range(1, 100)
# print the first 15 items
for i in items:
if i > 15:
return
print(i)
👇 Continue Reading
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)
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.
Reza Lavarian Hey 👋 I’m a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rlavarian
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
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
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 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
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
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
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.