Variable scoping in Python
In python, variables defined in a function is only local to that function.
def myfunct(): i = 1 return "Hello World" i = print myfunct() print i |
When you run the code above, it would spit out:
`
Hello
0
`
In order to manipulate a variable within the function defined in main, we need to use ‘global‘.
def myfunct(): global i i = 1 return "Hello World" i = print myfunct() print i |
When you run the code above, it would spit out:
`
Hello
1
`