The basics of syntax

INPUT · Slides

Changing what is inside

01 / 06

Put something in again and it replaces what was there

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

The order you write it is everything

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

x = x + 1 is not a contradiction

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

Right first, left after

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.

  • work out number + 1 on the right → number is 10 right now, so 11
  • put that 11 into number on the left → number is now 11

The 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

You can put it in a different variable instead

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

Use it before you make it and you get an error

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 = 150

Result

NameError: name 'price' is not defined