Variables and Types
A variable is a name that refers to a value. Variables let your program remember things so you can use them later.
A good way to picture it: a variable is a label stuck on a value. age = 36 sticks the label age on the value 36. Whenever you write age, Python looks up which value that label is stuck on.
Creating variables
You create a variable by assigning a value to a name with =:
name = "Ada" age = 36 print(name) print(age) print(name, "is", age, "years old")
Read age = 36 as "age now refers to 36". The = sign means "store this value", not "equals" as in maths.
Changing a variable
Variables can be reassigned at any time: the label moves to the new value.
Predict first: what will each
score = 10 print(score) score = 25 print(score) score = score + 5 # take the current value, add 5, store the result print(score)
The last line looks odd if you think of = as "equals". Python works it out in two steps: first it calculates the right side (25 + 5), then it stores the result in score.
Naming rules
Variable names:
- can contain letters, digits and underscores (
_), - can't start with a digit,
- are case-sensitive (
age,AgeandAGEare three different variables), - can't be a Python keyword such as
if,fororclass.
By convention, Python programmers use snake_case: lowercase words joined with underscores. Good names describe what the value is, like total_price rather than tp.
user_name = "sam" # good total_price = 9.99 # good 2nd_place = "Bo" # SyntaxError: starts with a digit
Basic data types
Every value in Python has a type: is it a whole number, a decimal number, some text? These are the ones you'll use most:
| Type | Meaning | Examples |
|---|---|---|
int |
Whole numbers | 42, -7, 0 |
float |
Decimal numbers | 3.14, -0.5, 2.0 |
str |
Text (strings) | "hello", 'Python' |
bool |
True or false | True, False |
NoneType |
"No value" | None |
int is short for integer and str for string. None is a special value meaning "nothing here yet".
Use the built-in type() function to find out the type of any value:
count = 42 price = 19.99 language = "Python" is_ready = True result = None print(type(count)) print(type(price)) print(type(language)) print(type(is_ready)) print(type(result))
The type matters because it decides what you can do with a value. You can do maths with numbers, but not with text. Numbers get a lesson of their own next.
A variable can change type
You never declare a type in Python. A variable simply takes the type of whatever value it currently holds, and it can hold a different type later:
thing = 10 print(thing, type(thing)) thing = "ten" print(thing, type(thing))
Converting between types
"25" (text) and 25 (a number) look similar, but they're different types. To change a value's type, use the type's name like a function:
text = "25"
number = int(text) # str -> int
print(number + 5)
print(float("3.5") * 2) # str -> float
print(str(100) + " points") # int -> str
print(int(9.99)) # float -> int (drops the decimals)Mixing text and numbers without converting raises a TypeError. Run this to see it:
age = 30
print("I am " + age + " years old")Python refuses to guess whether you meant maths or joining text. Fix it by converting with str(age), or by using an f-string.
f-strings
An f-string has an f before the opening quote. It lets you put variables, and even small calculations, inside curly braces {}:
name = "Ada"
age = 36
print(f"{name} is {age} years old")
print(f"Next year {name} will be {age + 1}")f-strings convert the values for you, so they're the easiest way to mix text and numbers. You'll use them in almost every lesson from here on.
Swapping two variables
You can assign several variables in one line by separating them with commas. This gives a neat trick for swapping two values:
a = "left" b = "right" a, b = b, a print(a, b)
Later, in the User Input lesson, you'll let the person running your program type in the values instead of writing them into the code.
Exercises
Exercise 1: Area of a rectangle
Create variables width and height with the values 7 and 4.5, calculate the area, and print it using an f-string: The area is 31.5.
width = height =
Put a number after each =, then calculate area = width * height.
Print with an f-string: print(f"The area is {area}").
Exercise 2: Add two numbers stored as text
The two variables below hold strings. Convert them and print their sum, which should be 42, not "1527".
first = "15" second = "27" print(first + second)
Right now + joins the two strings together. Convert them to numbers first.
int(first) turns the text "15" into the number 15.
Exercise 3: Swap the values
Swap the values of cup_a and cup_b so the program prints coffee tea.
cup_a = "tea" cup_b = "coffee" # swap here print(cup_a, cup_b)
Python can swap two variables in a single line using commas.
Write cup_a, cup_b = cup_b, cup_a before the print.
Exercise 4: Check the types
Print the type of each value: 3, 3.0, "3" and 3 > 2. Can you predict each one before running?
# print the type of each value
Put type() around each value, inside print(), like print(type(3)).
3 > 2 is a comparison. Think about what kind of value a comparison gives back.
Summary
- A variable is a name for a value, created with
=. - Common types:
int,float,str,bool,None. Check one withtype(). - A variable can hold any type of value, and can switch to a different type later.
- Convert with
int(),float()andstr(). Text and numbers don't mix without converting. - Use f-strings like
f"{name} is {age}"to build readable output.