+ 2
How to return a variable of a local function to an outside variable?
example def hello(): x=input(hello, what is your name?) return x x= the value returned from hello I want to assign the result of the function hello() to a global variable in this case the global x. is this possible or would I have to use a function other than return?
2 Answers
+ 5
You can also use you global variable inside a function: it's just requiring to be declared as 'global' variable for write access:
var x = 42
def func():
print(x)
func()
will output 42 (global var is accessible for reading), but:
var x = 42
def func():
x = "spam"
print(x)
func()
print(x)
will output 'spam' and 42 on next line (x is considerated as local var as you assign a value to it)... however, doing:
var x = 42
def func():
global x
x = "spam"
print(x)
func()
print(x)
... will output 2 times 'spam' on 2 separated lines (x inside function is declared as global, so the assignment will write the global variable) ;)
+ 3
In your example, you just have to do :
x=hello()