01 / 06
Put something in again and it replaces what was there
The basics of syntax
INPUT · Slides
01 / 06
Use = a second time on a variable you already made and the contents are replaced. The old value is gone.
A variable is not the value itself, it is a place to keep a value. That is why swapping works.
weather = "sunny"print(weather)weather = "rainy"print(weather)Result
sunny rainy
02 / 06
If the contents can change, then when you show it decides what you see.
A program runs from the top down, so where you put your print matters. In the example below, the print sits after the second assignment, so rainy comes out.
weather = "sunny"weather = "rainy"print(weather)Result
rainy
03 / 06
This is the fun part. If number = number + 1 looks impossible to you, that is because you are still reading = as "is equal to".
= means "put into". So that line says "take what is in number now, add 1, and put it back into number".
number = 10number = number + 1print(number)Result
11
04 / 06
Why can you read it that way? Because = works out the right-hand side first and then puts it into the left.
So number = number + 1 goes like this.
number + 1 on the right → number is 10 right now, so 11number on the left → number is now 11The number on the right is the old value; the one on the left is the container. Same name, different jobs.
score = 100score = score - 30score = score - 20print(score)Result
50
05 / 06
Rather than overwriting, you can keep the result under a new name. The original stays as it was.
Which is better depends on the moment. If you need the old value later, use a new name; if you are done with it, overwrite.
base = 100with_tax = base * 1.1print(base)print(with_tax)Result
100 110.00000000000001
06 / 06
Reach for a variable you have not made yet and you get a NameError.
It means "I do not know that name". A variable only works below the line that makes it. A typo gives you the same error, so check your spelling too.
print(price)price = 150Result
NameError: name 'price' is not defined