Syntaxerror return outside function ошибка

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

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

🚫 SyntaxError: ‘return’ outside function

This post was originally published on decodingweb.dev as part of the Python Syntax Errors series.

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

Enter fullscreen mode

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:

def isEven(value):
  remainder = value % 2

  # if the remainder of the division is zero, it's even
return remainder == 0

Enter fullscreen mode

Exit fullscreen mode

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

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Let’s see another example:

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

Enter fullscreen mode

Exit fullscreen mode

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

Enter fullscreen mode

Exit fullscreen mode

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:

items = range(1, 100)

# print the first 15 items
for i in items:
  if i > 15:
    return
  print(i)

Enter fullscreen mode

Exit fullscreen mode

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)

Enter fullscreen mode

Exit fullscreen mode

And that’s how you’d fix the error «SyntaxError: ‘return’ outside function» in Python.

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.

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

A return statement sends a value from a function to a main program. If you specify a return statement outside of a function, you’ll encounter the “SyntaxError: ‘return’ outside function” error.

In this guide, we explore what the “‘return’ outside function” error means and why it is raised. We’ll walk through an example of this error so you can figure out how to solve it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

SyntaxError: ‘return’ outside function

Return statements can only be included in a function. This is because return statements send values from a function to a main program. Without a function from which to send values, a return statement would have no clear purpose.

Return statements come at the end of a block of code in a function. Consider the following example:

def add_two_numbers(x, y):
	answer = x + y
	return answer

Our return statement is the final line of code in our function. A return statement may be used in an if statement to specify multiple potential values that a function could return.

An Example Scenario

We’re going to write a program that calculates whether a student has passed or failed a computing test. To start, let’s define a function that checks whether a student has passed or failed. The pass-fail boundary for the test is 50 marks.

def check_if_passed(grade):
	if grade > 50:
		print("Checked")
		return True
	else: 
		print("Checked")
return False

Our function can return two values: True or False. If a student’s grade is over 50 (above the pass-fail boundary), the value True is returned to our program. Otherwise, the value False is returned. Our program prints the value “Checked” no matter what the outcome of our if statement is so that we can be sure a grade has been checked.

Now that we have written this function, we can call it in our main program. First, we need to ask the user for the name of the student whose grade the program should check, and for the grade that student earned. We can do this using an input() statement:

name = input("Enter the student's name: ")
grade = int(input("Enter the student's grade: "))

The value of “grade” is converted to an integer so we can compare it with the value 50 in our function. Let’s call our function to check if a student has passed their computing test:

has_passed = check_if_passed(grade)
if has_passed == True:
	print("{} passed their test with a grade of {}.".format(name, grade))
else:
	print("{} failed their test with a grade of {}.".format(name, grade))

We call the check_if_passed() function to determine whether a student has passed their test. If the student passed their test, a message is printed to the console telling us they passed; otherwise, we are informed the student failed their test.

Let’s run our code to see if it works:

  File "test.py", line 6
	return False
	^
SyntaxError: 'return' outside function

An error is returned.

The Solution

We have specified a return statement outside of a function. Let’s go back to our check_if_passed() function. If we look at the last line of code, we can see that our last return statement is not properly indented.

…
	else: 
		print("Checked")
return False

The statement that returns False appears after our function, rather than at the end of our function. We can fix this error by intending our return statement to the correct level:

	else: 
		print("Checked")
return False

The return statement is now part of our function. It will return the value False if a student’s grade is not over 50. Let’s run our program again:

Enter the student's name: Lisa
Enter the student's grade: 84
Checked
Lisa passed their test with a grade of 84.

Our program successfully calculates that a student passed their test.

Conclusion

The “SyntaxError: ‘return’ outside function” error is raised when you specify a return statement outside of a function. To solve this error, make sure all of your return statements are properly indented and appear inside a function instead of after a function.

Now you have the knowledge you need to fix this error like an expert Python programmer!

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

Спасибо!


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

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

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

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

‘return’ outside function

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


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

04 июн. 2023, в 13:54

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

04 июн. 2023, в 13:43

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

04 июн. 2023, в 13:14

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

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

Понравилась статья? Поделить с друзьями:
  • Syntaxerror invalid syntax python ошибка
  • Svensson body labs ошибка err4
  • Syntaxerror cannot assign to operator ошибка
  • Sven coop ошибка fatal error
  • Syntax error at or near ошибка