Skip to content

Variables and values

Goal: store information in variables, print it inside sentences, and ask the user for input.

Why this matters

In the last lesson every program printed the same thing every time. That is not very useful. Real programs remember things: a name, a score, a price. In Python you remember things with variables.

What is a variable?

A variable is a name that points to a value. You create one with the equals sign:

variables.py
name = "Ada"
age = 36
height = 1.65

print(name)
print(age)
print(height)

Run it and you get:

Ada
36
1.65

Read the first line as "let name be "Ada"". From then on, whenever you write name, Python uses the value "Ada".

The equals sign is not a question

In math, = asks whether two things are equal. In Python, = is an instruction: put this value in that name. The name is always on the left, the value on the right.

Three kinds of values

The example above uses three different kinds of value, and Python treats each a little differently:

Value What it is Python calls it
"Ada" text, in quotes a string, or str
36 a whole number an integer, or int
1.65 a number with a decimal point a float

Notice that 36 has no quotes. "36" with quotes would be a string, a piece of text that happens to look like a number. You can do math with 36 but not with "36". This difference will matter in a moment.

Naming rules

Python is picky about names. A variable name:

  • can contain letters, digits, and underscores: score, player_1, total_cost
  • cannot start with a digit: 1st_place is not allowed
  • cannot contain spaces: write first_name, not first name
  • is case-sensitive: Name and name are two different variables

By convention, Python programmers write names in lowercase with underscores between words. This style is called snake_case. Pick names that say what the value means. age is better than a, and price_per_kilo is better than p.

Changing a variable

You can give a variable a new value at any time. The old value is forgotten:

score = 0
print(score)
score = 10
print(score)
0
10

Printing variables inside text

You will often want to mix variables into a sentence. The neatest way is an f-string: put the letter f right before the opening quote, then wrap each variable in curly braces.

fstrings.py
name = "Ada"
age = 36

print(f"My name is {name} and I am {age} years old.")
print(f"Next year I will be {age + 1}.")
My name is Ada and I am 36 years old.
Next year I will be 37.

Anything inside { } is evaluated by Python and dropped into the text. That includes math, as the second line shows.

Forgot the f?

Without the f, Python prints the braces literally: My name is {name}. If you see curly braces in your output, check for the missing f.

Asking the user for input

So far, values were typed into the program by you. The input() function lets the person running the program type a value.

greeting.py
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")

Run it. The program prints the question, then pauses and waits for you to type something and press Enter:

What is your name? Grace
Nice to meet you, Grace!

The text inside input(...) is the prompt shown to the user. Whatever they type is handed back and stored in name.

Input is always text

Here is the catch: input() always gives you a string, even if the user types a number. Try this and see it break:

age = input("How old are you? ")
print(f"Next year you will be {age + 1}.")
How old are you? 36
TypeError: can only concatenate str (not "int") to str

Python is saying: you asked me to add a string and a number, and I don't know how to do that. The fix is to convert the text into an integer with int():

age_next_year.py
age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")
How old are you? 36
Next year you will be 37.

You can do the conversion in one step: age = int(input("How old are you? ")). Both styles are fine. For decimal numbers use float() instead of int().

Try it

Write a program that asks for your favourite number, then prints that number times ten. Remember to convert the input.

Common mistakes

NameError: name 'nmae' is not defined

You used a variable that was never created, usually a typo. Python reports the misspelled name, so read it carefully.

SyntaxError: cannot assign to literal

The value and name are swapped, like 36 = age. The name must be on the left of the =.

ValueError: invalid literal for int() with base 10: 'abc'

You called int() on text that is not a number. For now, make sure to type a number when the program asks for one. Later in the course you will learn how to handle this gracefully.

Exercises

  1. Personal greeting. Ask for the user's name and city, then print one sentence that uses both.
  2. Number tricks. Ask for a number and print it doubled, then print it squared (multiplied by itself).
  3. Mad libs. Ask the user for an animal, a food, and a place. Then print a short silly story that uses all three.
Solution 1
name = input("What is your name? ")
city = input("Which city do you live in? ")
print(f"Hello {name} from {city}! Welcome to Python.")
Solution 2
number = int(input("Type a number: "))
print(f"{number} doubled is {number * 2}.")
print(f"{number} squared is {number * number}.")

number * number works, and so does number ** 2. The ** operator means "to the power of".

Solution 3
animal = input("Name an animal: ")
food = input("Name a food: ")
place = input("Name a place: ")

print(f"Yesterday I saw a {animal} eating {food} in {place}.")
print(f"The {animal} looked very happy.")

Summary

  • A variable stores a value under a name: age = 36.
  • Strings are text in quotes. Integers and floats are numbers, without quotes.
  • Use snake_case names that describe the value.
  • Put an f before a string and use {braces} to insert variables into text.
  • input() asks the user for a value and always returns a string. Convert with int() or float() when you need a number.

Next: Numbers and math