0 votes
1 view
in Python by (47.8k points)

I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:

if __name__ == '__main__':

x = 1 

print x

In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes and prints 1. Can anyone explain this behaviour? Are all variables created in a module global/available to the entire module?

1 Answer

0 votes
by (107k points)

The scope of a variable initialized in an if the statement is the same as "local scope", and actually code like this is common in Python:

if condition: 

x = 'something' 

else:

x = 'something else'

use(x)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...