I see that it's possible to define a variable inside a scope, but then refer to it outside that scope. For instance, the following code works:
if condition:
x = 5
else:
x = 10
print x
However, this strikes me as a bit weird. If you tried to do this in C, the variable X would not be scoped properly:
if(condition) { int x = 5; }
else { int x = 10; }
print x; // Doesn't work: x is unavailable!
The solution, in C anyway, is to declare X first, THEN figure out what do to with it:
int x;
if(condition) { x = 5; }
else { x = 10; }
print x; // Works!
So, in Python, my instinct is to write code like this:
x = None
if condition:
x = 5
else:
x = 10
print x
However, I realize Python doesn't require me to do this. Any suggestions? Is there a style guideline for this scenario?
Python global keyword is used to change the scope of variables. By default variables inside the function has local scope. Means you can't use it outside the function. Simple use global keyword to read and write a global variable inside a function.
The scope of a name or variable depends on the place in your code where you create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule. The letters in the acronym LEGB stand for Local, Enclosing, Global, and Built-in scopes.
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.
Blocks do not create a new scope in Python. Modules, classes, and functions do.
Also:
x = 10
if condition:
x = 5
print x
or:
x = 5
if not condition:
x = 10
print x
My suggestion:
Write Python, not C.
In Python we use blocks. An if
is a block. A block doesn't necessarily mean a different scope in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With