Syntaxerror 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):
        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 “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.

fix syntaxerror 'return' outside function

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 Raj

    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

Syntaxerror return outside function python
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 return outside function python
return outside function python

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

SyntaxError can't assign to function call in python
SyntaxError can’t 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

SyntaxError can't assign to function call in python
SyntaxError can’t assign to function call in python

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

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Denis

@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

Спасибо!


  • Вопрос задан

    более года назад

  • 1257 просмотров

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

‘return’ outside function

Пригласить эксперта


  • Показать ещё
    Загружается…

30 мая 2023, в 00:55

125000 руб./за проект

30 мая 2023, в 00:34

1000 руб./за проект

29 мая 2023, в 23:21

2000 руб./за проект

Минуточку внимания

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.

Понравилась статья? Поделить с друзьями:
  • Как правильно найти нужную информацию
  • Нарушение осанки у подростков как исправить
  • Как найти контакт в адресную книгу
  • Как найти комментарий на гугл
  • Такую подругу как ты трудно найти