+ 4

Variables inside and ouside a function in Python?

I would like to know how can I set a variable inside a function (or change it's value) and then use it outside the function.

7th Dec 2016, 6:29 PM
Ivan Truenow
Ivan Truenow - avatar
6 ответов
+ 3
Thank you very much for your answers, explanations and examples. You helped me a lot!!
8th Dec 2016, 2:28 AM
Ivan Truenow
Ivan Truenow - avatar
+ 2
you can't get viariables defined inside a function, if you don't return it. If you set a variable inside a function, they only exist inside the function. You can modify them if they are defined outside. You can return a list/array if you want more than 1 variable.
7th Dec 2016, 6:33 PM
Nahuel
Nahuel - avatar
+ 2
def something(): z=2 global z return (z+4) global makes it global not local.
8th Dec 2016, 2:07 AM
Murat Ahmedovich
Murat Ahmedovich - avatar
+ 1
"I would like to know how can I set a variable inside a function (or change it's value) and then use it outside the function." Here's an example: x = 0 def myFunc(num): num = num + 5 return num x = myFunc(x) print(x) I'll do a step by step of what I just did: >python, set the variable "x" to "0" >python, create a new function called "myFunc" that accepts one input named "num" >python, set the variable "num" to equal the current value of "num" and add "5" >python, return to the outside: the value of "num" >python, run the function called "myFunc", use the variable "x" as input. Then whatever output the function sends back, place it inside the variable "x" >python, print the value of "x" This is an example of giving a function a value, and the function returning a new/changed value back that you can later use.
7th Dec 2016, 6:46 PM
Sapphire
+ 1
A function has its own space ("namespace") in terms of variable names living there, and the interpreter should look outside in the enclosing context if it encounters a name that is not defined. However, I've seen that this does not always work, and find it often best to declare variables in the module and refer to those in a function using the global (+var name) keyword right after the function header. You can also use the nonlocal keyword for referring to a variable name just one namespace up.
14th Feb 2017, 12:20 AM
Torbjørn
Torbjørn - avatar
0
Just do as you do elsewhere
7th Dec 2016, 6:32 PM
Rishi Anand
Rishi Anand - avatar