1.2 Variables

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

1.2 Variables

A variable is a name for a value. Instead of typing the same number or word again and again, you store it once and use the name.

Giving a value a name

You assign a value to a variable with =:

age = 12
name = "Sam"
score = 0

The name goes on the left, the value on the right. After that, whenever you use age, Python uses 12.

Rules for variable names

Using variables

You can use variables in print() and in calculations:

favourite_number = 7
print(favourite_number)           # 7
print(favourite_number + 3)       # 10
message = "My favourite number is"
print(message, favourite_number)  # My favourite number is 7

Overwriting

If you assign a new value to the same variable, the old value is replaced:

lives = 3
print(lives)  # 3
lives = 2
print(lives)  # 2

Getting input from the user

You can ask the user to type something with input():

name = input("What is your name? ")
print("Hello,", name)

Whatever they type (until Enter) is stored as a string. If you want a number, you have to convert it: int(input("Enter a number: ")).

Mini project: Store and print

  1. Create variables for your favourite number and a short message.
  2. Print them together in one sentence.
  3. Use input() to ask for their name and then print “Hello, [name]”.

Next: 1.3 Operators — maths and comparisons.