I believe your question is about scope. In the above example, a new memory address for var x
is created on the first line and any code on lines 2,3,4 that access x
can read/write to that variable.
There are only two rules here that we need to follow:
x
must be declared before print
so that print can access that piece of memory
print
must be in the same or inner scope to access 'x'
Example 1 - valid (because we follow rules 1 and 2)
x = 1
print x
Example 2 - valid (because we follow rules 1 and 2)
x = 1
while x < 10:
print x
x = x + 1
Example 3 - valid (because we follow rules 1 and 2)
x = 1
while x < 10:
print x
x = x + 1
print x
Example 4 - NOT valid (because we don't follow rule 1 and print
is accessing a variable that has not yet been created in memory)
print x
x = 1
Example 5 - NOT valid (because we don't follow rule 2 and print
doesn't have access to our variable's scope, x
no longer exists in memory)
y = 1
while y < 5:
x = 1
y = y + 1
print x
It would do you good to read this entire section on variable lifetime and scope in python all the way through Exercise 1 for good practice.