Chapter 02 ยท Getting Started
Variables & Data Types
A program that can only print fixed words is a poster. To make it come alive, it needs to remember things. That's what variables are for.
A variable is a labelled box. You put something in the box and write a name on the outside. Later you use the name to get the thing back โ without caring exactly where it's stored.
Making a variable
You create a variable by giving it a name, an = sign, and a value:
name = "Godfrey"
age = 25
print(name)
print(age)
The = means "put the value on the right into the box on the left." Now name
holds the text and age holds the number, and we can use them anywhere.
The main types of data
| Type | What it is | Example |
|---|---|---|
| str (string) | Text, in quotes | "hello", "260" |
| int (integer) | A whole number | 25, -4, 1000 |
| float | A number with a decimal point | 3.14, 19.99 |
| bool (boolean) | True or False โ a yes/no value | True, False |
You don't declare the type โ Python works it out from the value. A number in quotes is text; the same number without quotes is a real number you can do maths with.
Variables can change
That's why they're called variable โ the value can vary:
score = 10
print(score)
score = score + 5
print(score)
Putting values into text with f-strings
The cleanest way to mix variables into a message is an f-string โ put f
before the quotes and wrap variable names in { }:
name = "Godfrey"
age = 25
print(f"My name is {name} and I am {age} years old.")
Make three variables โ your name, your age, and your favourite colour โ then print one sentence using an f-string that uses all three.
Variable names can use letters, numbers and underscores, but can't start with a number or contain
spaces. Use clear names: total_price beats tp. And Python cares about case โ
Name and name are two different boxes.
Recap
- A variable stores a value under a name:
age = 25. - The main types are str, int, float, bool.
- Quotes make text; no quotes makes a real number.
- f-strings (
f"... {name} ...") drop variables neatly into text.