As I muddle my way through trying to learn how to code (in python) I’ve hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don’t know how to get it back properly (this method does not work.)
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
I am ‘expecting’ b to be available after the function call, as I have returned it… I appreciate this me not understanding properly how to implement/manage variables
Thanks.
I think this is what you want to do:
It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular.
A couple of other things.
In the line
a = "foo", a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular).It looks like you are having trouble understanding an aspect of how variables work called ‘scope’. When you declared the variable
binside offunc_1(), it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been calledb.I’m not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration.
Here is an example of how a “normal” program might be set up: