Codiqo

Learn Python · lesson 3 of 60 · about 7 minutes

Variables

Store a value once under a name, use it in every message, and update it when it changes.

What you'll learn

  • Store a value in a variable
  • Use a variable more than once
  • Give a variable a new value

Write it once

Your assistant should greet you by name, and sign off by name too. Type your name into every message and one day you'll change it in one place and forget another. Store it once, in a variable, and use the variable everywhere.

name = "Ada" makes a variable called name holding "Ada". Here = stores a value: it doesn't ask whether two things are equal.

One variable, used in two messages

name = "Ada"
print("Good morning,", name)
print("Have a great day,", name)

Output

Good morning, Ada
Have a great day, Ada

Variables can change

Some values change while the program runs: tasks get done, money gets saved. Give a variable a new value with = again, and the old one is gone.

tasks = tasks - 1 works out the right side first, using the old value, then stores the answer.

Step through it to watch tasks change

tasks = 3
tasks = tasks - 1
tasks = tasks + 2
print("Tasks left:", tasks)

Output

Tasks left: 4

Tip

Python names are lowercase with underscores between words: first_name, weekly_savings. No spaces, and a name can't start with a number.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.