educative.io

Scope for the new_num variable

Hi, this python course is amazing, designed in a good way, passing through if else statement, i saw this page where `
num = 10
if num > 5:
num = 20 # Assigning a new value to num
new_num = num * 5 # Creating a new value called newNum

The if condition ends, but the changes made inside it remain

print(num)
print(new_num)`

and execution prints the new_num value outside the if code block, since it was created inside if statement, why is it accessible outside what is the scope of this variable ?

1 Like

In Python, a variable’s lifetime is bound by the enclosing function, class, or module. Loops and conditional statements do not affect it. Hence, a new variable can be created inside an if block or a for loop, and it will still exist after the block/loop ends.

However, if the control block was inside a function, the variable’s lifetime would be restricted to the function’s scope, and not outside it.

Hope this helps.

5 Likes