Return variables python functions

How to Return a Global and Local Variable from a Python Function?

Be on the Right Side of Change

πŸ’¬ Question: How to return a global variable from a Python function. And how to return a local variable?

First, have a look at the overview figure that shows how to return a local and global variable from a Python function using a simple example:

Let’s dive into this example in more detail and answer the question of how to return a local variable first. We’ll learn how to return a global variable from a function afterward by building on what we’ve learned. πŸ‘‡

Return a Local Variable From Function

If you assign a value to a variable inside a function scope, Python will create a new local variable. This new local variable will be created even if you have already defined the same variable outside the function scope.

🐍 Changing the local variable doesn’t change the global variable. The change is only visible inside the function scope. The local variable overshadows the global variable.

The following example shows how you can create and return a local variable x = ‘alice’ from a function that overshadows the global variable x = 42 .

x = 42 def f(): x = 'alice' return x print(f()) # alice # Has the global variable x changed? print(x) # Output: 42 - no it has not changed.

Return a Global Variable From a Function

To return a global variable x from a Python function, add the line global x inside the function scope. Each time you read or write the variable inside the function after this line, you’ll read or write the global variable. To return the global variable then simply write return x .

The following code shows that changing the global variable inside the function has side effects, i.e., it can be seen from the outside in contrast to the previous example when changing the local variable x inside the function didn’t affect the global variable x .

x = 42 def f(): global x x = 'alice' return x print(f()) # alice # Has the global variable x changed? print(x) # Output: alice - yes it has changed.

Example – Analyzing the Local and Global Scope

To check the local and global scope, i.e., which variables are defined locally and globally, you can use the dir() function like so:

x = 42 def f(): print(dir()) # [] global x x = 'alice' print(dir()) # [] return x print(dir()) # ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f', 'x'] print(f()) # alice # Has the global variable x changed? print(x) # Output: alice - yes it has changed.

This shows that the local scope doesn’t change inside the function because Python works on the global variable.

Note that without the global x definition inside the function, the variable x would in fact be a local variable as can be seen in the highlighted area:

x = 42 def f(): print(dir()) # [] x = 'alice' print(dir()) # ['x'] return x print(dir()) # ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f', 'x'] print(f()) # alice # Has the global variable x changed? print(x) # Output: alice - yes it has changed.

Okay, let’s close this tutorial with a short recap of the dir() function for learning and ease of understanding of the previous code snippet.

Python dir() Recap

Python dir() Visual Explanation

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scopeβ€”the namespace of your current module.

If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope.

Thus, dir() returns all names in a given scope.

Summary

Per default, Python returns variables in the local scope, not in the global scope. To explicitly return a global variable x , use the line global x before changing or returning it from the function.

Thanks for reading this tutorial! ❀️ Feel free to join my free email academy and download our Python cheat sheets for maximum learning efficiency (I’m German, so I care a lot about efficiency). πŸ˜‰

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change πŸš€

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. πŸ€–
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources πŸ§‘β€πŸ’»

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses πŸ‘‘ to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

Get Variable from Function in Python

A function is a reusable piece of code that can be called at different places in a program. A function can execute some statements when called and return some value if desired. Any variable declared within the function cannot be accessed from the outside.

We will discuss how to get variable from function in Python.

Using the return statement to get variable from function in Python

The return statement in Python is used to return some value from a function in Python. Since we cannot access the variable defined within the function from the outside, we can return it using the return statement to get variable from function in Python.

We can also return multiple variables. For this, we can use objects like lists, dictionaries, and more. We will store the variables in one such object and return it from the function.

In the above example, we return a dictionary from the function. We access the variable values using the variable’s key from the dictionary and print it.

Using attributes to get variable from function in Python

Everything is an object in Python, even functions. We can assign functions with some arbitrary values that can work as attributes. These values can be accessed from outside a function. This way, we can get variable from function in Python.

In the above example, we assign an attribute value to the function. We first call this function and then we can use this variable using the function name.

Further reading:

Get variable name as String in Python
Check if variable is String in Python

Conclusion

In this tutorial, we discussed how to get variable from function in Python. There is no direct way to access a variable declared within the function from outside. So, to get variable from function in Python, we can directly return the value. We discussed how to return single and multiple variables. Another way to get variable from function in Python is by assigning them as attributes of the function. This way, we can access the attribute values after calling the function.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

Π§ΠΈΡ‚Π°ΠΉΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅:  Html all tags and codes
ΠžΡ†Π΅Π½ΠΈΡ‚Π΅ ΡΡ‚Π°Ρ‚ΡŒΡŽ