I am a Python beginner and I am in the background of C / C ++. I am using Python 2.7.
I read this article: Pythons Namespace Beginner's Guide, Scope Resolution, and the LEGB Rule , and I think I have some understanding of Python about these technologies.
Today I realized that I can write Python code as follows:
if condition_1: var_x = some_value else: var_x = another_value print var_x
That is, var_x is still available, even if it does not define before if. Since I am from C / C ++ background, this is something new for me, as in C / C ++, var_x defined in the area enclosed by if and else, so you can no longer access it if you do not define var_x before if .
I tried to find answers on Google, but since I am not familiar with Python yet, I donβt even know where to start and what keywords I should use.
I assume that in Python, if does not create a new scope. All variables that were defined in if are only in the area in which the if is located, and therefore the variable is still available after if . However, if var_x in the above example is defined only in if , but not in else , a warning will be issued that print var_x may refer to a variable that cannot be defined.
I have some confidence in my own understanding. However, can someone help correct me if I'm wrong somewhere, or give a link to a document that discusses this ??
Thanks.
scope python
yaobin
source share