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. The name always goes on the left and the value on the right; 36 = age is an error.
Notice the difference between print(name) and print("name"). Without quotes, Python looks up the variable and prints its value, Ada. With quotes, it's just the text name.
A variable has to be created before you use it. Python runs from top to bottom, so using a name before its = line gives a NameError:
print(city) city = "Paris"
Swap the two lines and run it again.
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 print(score)
The last line looks odd if you think of = as "equals". Python works it out in two steps:
- It calculates the right side using the current value:
score + 5is25 + 5, which is30. - It stores the result in
score, replacing the old value.
The old value 25 isn't kept anywhere. A variable only ever holds its latest value.
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 contain spaces or symbols such as
-,!or., - 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.
| Name | OK? | Why |
|---|---|---|
user_name |
Yes | lowercase words joined with _ |
score2 |
Yes | digits are fine after the first character |
2nd_place |
No | starts with a digit |
user-name |
No | - is the minus sign, so Python reads user - name |
first name |
No | contains a space |
class |
No | a Python keyword |
Run this to see the error a bad name gives. Because it's a SyntaxError, Python refuses to run any of the code, not even the first line:
print("Starting")
2nd_place = "Bo"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".
A few details that trip people up:
True,FalseandNonestart with a capital letter.trueis just an unknown name.- A decimal point makes a
float, even when the number is whole:2.0is afloat,2is anint. - Quotes make a
str, even when what's inside looks like a number:"42"is text, not a number.
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))
Each line prints something like <class 'int'>. Read it as "the type is int". (Class is Python's word for a type.)
The type matters because it decides what you can do with a value. For example, + adds numbers but joins strings:
# two ints: adds them
print(2 + 3)
# two strings: joins them
print("2" + "3")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)
print(number + 5)
print(float("3.5") * 2)
print(str(100) + " points")
print(int(9.99))| Function | Turns a value into | Example | Result |
|---|---|---|---|
int() |
a whole number | int("25") |
25 |
float() |
a decimal number | float("3.5") |
3.5 |
str() |
text | str(100) |
"100" |
Converting doesn't change the original variable. int(text) gives back a new value, which is why the code stores it with number = int(text).
Two things to watch for with int():
- On a decimal number,
int()drops everything after the point. It doesn't round, soint(9.99)is9. - The text has to look like a whole number.
int("hello")andint("3.5")both stop with aValueError. (float("3.5")works.)
print(int("42"))
# not a whole number: ValueError
print(int("3.5"))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 the number to text:
age = 30
print("I am " + str(age) + " years old")That works, but all the + signs and spaces are fiddly to get right. f-strings, next, are the easier way.
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}")Inside the braces you can put a variable, or a small expression such as age + 1. Python works it out and puts the result into the text. Everything outside the braces is printed exactly as written.
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.
The most common mistake is forgetting the f. Without it, the braces are printed as ordinary text:
name = "Ada"
# no f: the braces are printed
print("Hello, {name}")
# with f: the value goes in
print(f"Hello, {name}")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:
x, y = 3, 7 print(x, y) a = "left" b = "right" a, b = b, a print(a, b)
x, y = 3, 7 gives x the first value and y the second. In a, b = b, a, Python reads both values on the right first ("right", "left") and only then stores them, so neither value gets lost.
Going deeper: Why not just a = b, then b = a? optional
That's the natural first try, but it loses a value:
a = "left" b = "right" # a is now "right"; "left" is gone a = b # so b gets "right" too b = a print(a, b)
Many other languages swap with a third, temporary variable that holds one value while you move the other. Python's a, b = b, a does that for you.
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
=(name on the left, value on the right). Create it before you use it. - Reassigning replaces the old value.
score = score + 5uses the current value, then stores the new one. - Names use letters, digits and
_, can't start with a digit, and are case-sensitive. Use snake_case. - Common types:
int,float,str,bool,None. Check one withtype(). - Convert with
int(),float()andstr().int()drops decimals, and text and numbers don't mix with+without converting. - Use f-strings like
f"{name} is {age}"to build readable output. Don't forget thef.
Know something worth teaching? Write your own tutorial with runnable examples and share it.