Reputation: 5714
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?
Upvotes: 7
Views: 421
Reputation: 798706
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
Upvotes: 17
Reputation: 89927
You're not creating a new scope, so there's no scoping problem.
However, note that if you do something like:
if foo:
x = 10
print x
You'll get a NameError raised if foo
is False, so you might come across a case where you actually do want to define your variable outside of the conditional (or add an else
to assign it None
.)
Upvotes: 0
Reputation: 12570
In your example, you might try this:
x = 10
if condiiton:
x = 5
print x
As for why Python doesn't have the same scoping rules as C (and C++ and Java), the short answer is that they're different languages. The long answer has to do with efficiency. In C, these scoping rules are all handled at compile time, there's no runtime overhead. In Python, it would have to store an inner scope in a new dict
, and that would add overhead. I'm sure there are other reasons, but this is a big practical one.
Upvotes: 0
Reputation: 117691
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.
Upvotes: 5