Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python let me define a variable in one scope, but use it in another?

Tags:

python

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?

like image 789
Stephen Gross Avatar asked Mar 16 '11 19:03

Stephen Gross


People also ask

How do I change the scope of a variable in Python?

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.

What does Python rely on to define scope in the code?

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.

What is nested scope in Python?

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.

Can we use same variable name in two methods Python?

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.


2 Answers

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
like image 167
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 18:09

Ignacio Vazquez-Abrams


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.

like image 30
orlp Avatar answered Sep 19 '22 18:09

orlp