1

Can someone tell me where I can find some information about the life of variables in if statement? In this code:

if 2 < 3:
   a = 3
else:
   b = 1
print(a)

It prints the variable a. But it seems to me a local variable of the if statement. In C infacts it gives me an error if I create the a variable in the if statement.

I think that this behaviour is because Python is an interpreted language. Am I right?

t3m2
  • 366
  • 1
  • 15
Giovanni
  • 79
  • 8
  • 1
    It will definitely print a because 2 is already less than 3, you basically declared your variable in the if statement. Now you can print (a). If you print (b) it won't work. – Sin Han Jinn Nov 15 '19 at 08:10
  • your print code is executing of same block either it will be a global or local currently it is global so currently if condition is true (which is true)then it will declare a variable a which will stick with current scope ( currently it is global) if you put this code inside function then it will be local to that function – Jadli Nov 15 '19 at 08:48

6 Answers6

5

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. However Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.

Taking into consideration your example:

if 2 < 3:
   a = 3
else:
   b = 1
print(a)

Note that a isn't declared or initialized before the condition unlike C or Java, In other words, Python does not have block-level scopes. You can get more information about it here

Paul
  • 448
  • 1
  • 6
  • 14
4

Interpretation and compilation have nothing to do with it, and being interpreted is not a property of languages but of implementations.
You could compile Python and interpret C and get exactly the same result.

In Python, you don't need to declare variables and assigning to a variable that doesn't exist creates it.
With a different condition – if 3 < 2:, for instance – your Python code produces an error.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
3

An if statement does not define a scope as it is not a class, module or a function --the only structures in Python that define a scope. Python Scopes and Namespaces

So a variable defined in an if statement is in the tightest outer scope of that if.

Fakher Mokadem
  • 1,059
  • 1
  • 8
  • 22
3

See: What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

This also applies to for loops which is completely unlike C/C++; a variable created inside the for loop will also be visible to the enclosing function/class/module. Even more curiously, this doesn't apply to variables created inside list comprehensions, which are like self-contained functions, i.e.:

mylist = [zed for zed in range(10)]

In this case, zed is not visible to the enclosing scope! It's all consistent, just a bit different from some other languages. Designer's choice, I guess.

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
2

The way c language and its compiler is written is that during compile time itself "declaration of certain identifiers are caught", i.e this kind of grammar is not allowed. you can call it a feature/limitation.

Python - https://www.python.org/dev/peps/pep-0330/ The Python Virtual Machine executes Python programs that have been compiled from the Python language into a bytecode representation.

However, python(is compiled and interpreted, not just interpreted) is flexible i.e you can create and assign values to variables and access them globally, locally and nonlocally(https://docs.python.org/3/reference/simple_stmts.html#grammar-token-nonlocal-stmt), there are many verities you can cook up during your program creation and the compiler allows it as this is the feature of the language itself.

coming to scope and life of variables , see the following description, it might be helpful

When you define a variable at the beginning of your program, it will be a global variable. This means it is accessible from anywhere in your script, including from within a function.

example:-

Program#1

a=1

if2<3
 print a

this prints a declared outside.


however, in the below example a is defined globally as 5, but it's defined again as 3, within a function. If you print the value of a from within the function, the value that was defined locally will be printed. If you print a outside of the function, its globally defined value will be printed. The a defined in function() is literally sealed off from the outside world. It can only be accessed locally, from within the same function. So the two a's are different, depending on where you access them from.

Program#2

a = 1

def random1():
    a = 3
    print(a)

function()
print(a)

Here, you see 3 and 5 as output.
forkdbloke
  • 1,505
  • 2
  • 12
  • 29
1

**The scope of a variable refers to the places that you can see or access a variable.

CASE 1:If you define a variable at the top level of your script or module or notebook, this is a global variable:**

>>> global_var = 3

>>> def my_first_func():
...     # my_func can 'see' the global variable
...     print('I see "global_var" = ', global_var, ' from "my_first_func"')

output:

my_first_func() I see "global_var" = 3 from "my_first_func"

CASE 2:Variables defined inside a function or class, are not global. Only the function or class can see the variable:

 >>> def my_second_func():
    ...     local_var = 10
    ...     print('I see "local_var" = ', local_var, 'from "my_second_func"')

Output:

my_second_func() I see "local_var" = 10 from "my_second_func"

CASE 3:But here, down in the top (global) level of the notebook, we can’t see that local variable:

Output:

>>> local_var
Traceback (most recent call last):
  ...
NameError: name 'local_var' is not defined
Jadli
  • 858
  • 1
  • 9
  • 17