Variables

Getting Started, lesson 4 of 5

👋 Getting Started, lesson 4 of 5

Variables

Store values under a name, reuse them and change them.

10 min

2 exercises

2 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

A variable is a name that refers to a value, like a label on a box. You create one with =, which means "store the value on the right under the name on the left".

After that, use the name anywhere you would use the value. Note there are no quotes around a variable name.

Example

Creating variables

Change name and age to your own details and run it again.

Variables can change. Assigning again replaces the old value. You can even use a variable's current value to compute its new one: score = score + 10 means "take the current score, add 10, store the result back in score".

Example

Updating a variable

Add a line score = score - 5 at the end, then print the score again.

Quiz

What does this print?

Exercise

Travel plans

  1. Set city to the name of any city (as text, in quotes).
  2. Set year to the number 2030 (no quotes).
  3. Run it to see your plans printed.

Naming rules. Names can contain letters, digits and underscores, but can't start with a digit or contain spaces. They are case-sensitive (Age and age are different). Python style is snake_case: lowercase words joined by underscores, like high_score.

Every value also has a type. The four basic ones: str (text), int (whole number), float (decimal number) and bool (True or False).

Example

Checking types

Notice that "7" in quotes is a str, not an int!

Quiz

Which of these is a valid variable name?

Exercise

Piggy bank

coins starts at 10. Update it in two steps:

  1. Add 5 coins.
  2. Then double the coins.

At the end coins should be 30. Update the variable itself, don't just print 30.