>>> Python for Beginners Chapter 02 of 10

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.

๐Ÿ“ฆ
Real-world analogy

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)
Godfrey 25

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

TypeWhat it isExample
str (string)Text, in quotes"hello", "260"
int (integer)A whole number25, -4, 1000
floatA number with a decimal point3.14, 19.99
bool (boolean)True or False โ€” a yes/no valueTrue, 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)
10 15

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.")
My name is Godfrey and I am 25 years old.
โœ๏ธ Try it yourself

Make three variables โ€” your name, your age, and your favourite colour โ€” then print one sentence using an f-string that uses all three.

Naming rules

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