Reputation: 163
When I attempt to print a value I get an error stating that the value is not defined.
def myFunc():
myValue = "Hello World!"
myFunc()
print(myValue)
I was expecting myValue to be printing "Hello World!" however this is not the case.
Upvotes: 0
Views: 598
Reputation: 36431
Some doc (Programming FAQ, Python 3.7.4) says:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.
Then your variable is local to the function that means that this variable doesn't exist outside it. So if you really need to access it outside, then declare it as global
:
def myFunc():
global myValue
myValue = "Hello World!"
print(myValue)
Upvotes: 0
Reputation: 326
You need to return that value and then define that your function will return something when you call it. Then, you print the value:
def myFunc():
myValue = "Hello World!"
return myValue
myValue = myFunc()
print(myValue)
or:
def myFunc():
myValue = "Hello World!"
print (myValue)
myFunc()
Upvotes: 2