By Rupert
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 = 0 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 = 0 print myfunct() print i
When you run the code above, it would spit out:
>>>
Hello
1
>>>
| Print article | This entry was posted by rupert on October 27, 2007 at 7:47 pm, and is filed under python. Follow any responses to this post through RSS 2.0. You can skip to the end and leave a response. Pinging is currently not allowed. |