Python return ошибка

The idea of this code is, the user presses the first button and enters what they want, then they press the second button and it prints it out. Can someone please tell me why my return statement is not working? It says that ‘variable’ is not defined. Thanks in advance for taking the time to read my question.

from tkinter import*

def fun():
    variable = input('Enter Here:')
    return variable


def fun_2():
    print(variable)


window = Tk()
button = Button(text = 'Button', command = fun )
button2 = Button(text = 'Button2', command = fun_2 )
button.pack()
button2.pack()


window.mainloop()

asked May 9, 2015 at 17:15

james hughes's user avatar

In python when you create a variable inside of a function, it is only defined within that function. Therefore other functions will not be able to see it.

In this case, you will probably want some shared state within an object. Something like:

class MyClass:
  def fun(self):
    self.variable = input('Enter Here:')

  def fun_2(self):
    print(self.variable)

mc = MyClass()

window = Tk()
button = Button(text = 'Button', command = mc.fun )
button2 = Button(text = 'Button2', command = mc.fun_2 )
button.pack()
button2.pack()

answered May 9, 2015 at 17:21

Martin Konecny's user avatar

Martin KonecnyMartin Konecny

57.2k19 gold badges137 silver badges157 bronze badges

fun() may return a value, but Tkinter buttons don’t do anything with that return value.

Note that I used the phrase return a value, not return a variable. The return statement passes back the value of an expression, not the variable variable here. As such, the variable variable is not made into a global that other functions then can access.

Here, you can make variable a global, and tell fun to set that global:

variable = 'No value set just yet'

def fun():
    global variable
    variable = input('Enter Here:')

Since you did use any assignment in fun2, variable there is already looked up as a global, and it’ll now successfully print the value of variable since it now can find that name.

answered May 9, 2015 at 17:20

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m295 gold badges4025 silver badges3320 bronze badges

The problem is in in fun2(). It does not get variable as an input parameter.

def fun_2(variable):
     print(variable)

But note that you have to call fun_2 now with the appropriate argument. Also, as the function stands right now, there is little point in having the function if you just do a print inside of it.

Take away message: variable is not global in Python, and as such you must pass it to each function that wants to use it.

answered May 9, 2015 at 17:23

Unapiedra's user avatar

UnapiedraUnapiedra

14.8k12 gold badges64 silver badges91 bronze badges

Raise, return, and how to never fail silently in Python.

I hear this question a lot: “Do I raise or return this error in Python?”

The right answer will depend on the goals of your application logic. You want to ensure your Python code doesn’t fail silently, saving you and your teammates from having to hunt down deeply entrenched errors.

Here’s the difference between raise and return when handling failures in Python.

When to raise

The raise statement allows the programmer to force a specific exception to occur. (8.4 Raising Exceptions)

Use raise when you know you want a specific behavior, such as:

raise TypeError("Wanted strawberry, got grape.")

Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you’ll get an unhandled exception message.

Raise is useful in cases where you want to define a certain behavior to occur. For example, you may choose to disallow certain words in a text field:

if "raisins" in text_field:
    raise ValueError("That word is not allowed here")

Raise takes an instance of an exception, or a derivative of the Exception class. Here are all of Python’s built-in exceptions.

Raise can help you avoid writing functions that fail silently. For example, this code will not raise an exception if JAM doesn’t exist:

import os


def sandwich_or_bust(bread: str) -> str:
    jam = os.getenv("JAM")
    return bread + str(jam) + bread


s = sandwich_or_bust("U0001F35E")
print(s)
# Prints "🍞None🍞" which is not very tasty.

To cause the sandwich_or_bust() function to actually bust, add a raise:

import os


def sandwich_or_bust(bread: str) -> str:
    jam = os.getenv("JAM")
    if not jam:
        raise ValueError("There is no jam. Sad bread.")
    return bread + str(jam) + bread


s = sandwich_or_bust("U0001F35E")
print(s)
# ValueError: There is no jam. Sad bread.

Any time your code interacts with an external variable, module, or service, there is a possibility of failure. You can use raise in an if statement to help ensure those failures aren’t silent.

Raise in try and except

To handle a possible failure by taking an action if there is one, use a tryexcept statement.

try:
    s = sandwich_or_bust("U0001F35E")
    print(s)
except ValueError:
    buy_more_jam()
    raise

This lets you buy_more_jam() before re-raising the exception. If you want to propagate a caught exception, use raise without arguments to avoid possible loss of the stack trace.

If you don’t know that the exception will be a ValueError, you can also use a bare except: or catch any derivative of the Exception class with except Exception:. Whenever possible, it’s better to raise and handle exceptions explicitly.

Use else for code to execute if the try does not raise an exception. For example:

try:
    s = sandwich_or_bust("U0001F35E")
    print(s)
except ValueError:
    buy_more_jam()
    raise
else:
    print("Congratulations on your sandwich.")

You could also place the print line within the try block, however, this is less explicit.

When to return

When you use return in Python, you’re giving back a value. A function returns to the location it was called from.

While it’s more idiomatic to raise errors in Python, there may be occasions where you find return to be more applicable.

For example, if your Python code is interacting with other components that do not handle exception classes, you may want to return a message instead. Here’s an example using a tryexcept statement:

from typing import Union


def share_sandwich(sandwich: int) -> Union[float, Exception]:
    try:
        bad_math = sandwich / 0
        return bad_math
    except Exception as e:
        return e


s = share_sandwich(1)
print(s)
# Prints "division by zero"

Note that when you return an Exception class object, you’ll get a representation of its associated value, usually the first item in its list of arguments. In the example above, this is the string explanation of the exception. In some cases, it may be a tuple with other information about the exception.

You may also use return to give a specific error object, such as with HttpResponseNotFound in Django. For example, you may want to return a 404 instead of a 403 for security reasons:

if object.owner != request.user:
    return HttpResponseNotFound

Using return can help you write appropriately noisy code when your function is expected to give back a certain value, and when interacting with outside elements.

The most important part

Silent failures create some of the most frustrating bugs to find and fix. You can help create a pleasant development experience for yourself and your team by using raise and return to ensure that errors are handled in your Python code.

I write about good development practices and how to improve productivity as a software developer. You can get these tips right in your inbox by signing up below!

When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

I get the following error

SyntaxError: 'return' outside function

I’ve carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

asked Oct 20, 2011 at 20:54

Jeff's user avatar

3

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

answered Oct 20, 2011 at 21:05

Raymond Hettinger's user avatar

Raymond HettingerRaymond Hettinger

214k62 gold badges378 silver badges481 bronze badges

5

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Antonio's user avatar

Antonio

19.3k12 gold badges98 silver badges195 bronze badges

answered Feb 9, 2014 at 2:09

buzzard51's user avatar

buzzard51buzzard51

1,3502 gold badges23 silver badges40 bronze badges

1

To break a loop, use break instead of return.

Or put the loop or control construct into a function, only functions can return values.

answered Oct 20, 2011 at 21:45

Jürgen Strobel's user avatar

0

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

answered Mar 28, 2017 at 22:13

Eugene Yarmash's user avatar

Eugene YarmashEugene Yarmash

141k40 gold badges322 silver badges376 bronze badges

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

.



  1. 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.


  2. '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

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.

Понравилась статья? Поделить с друзьями:
  • Python requests обработка ошибок
  • Python requests коды ошибок
  • Python pyqt5 сообщение об ошибке
  • Python postgresql обработка ошибок
  • Python manage py createsuperuser ошибка