Coding Hub  /  Python

variables & types

Storing values, naming them well, and what breaks when types mix. The last three entries are where nearly every beginner bug comes from.

Storing a value

A variable is a name pointing at a value. That is the whole idea.

01 Making a variable

One equals sign means put this value in this name. Python needs no keyword and no type declaration — the name springs into existence when you assign to it.

= assigns. == compares. Writing if x = 5 is a SyntaxError, and it is the error you will make most often in your first month.

variables.py
name = "Ada"          # a string
age = 36              # an integer
height = 1.7          # a float
is_student = False    # a boolean

# Reassigning is fine, and the type can change
age = age + 1
age = "thirty-seven"  # legal, though usually a mistake

# Several at once
x, y = 3, 4

02 Naming things

Python's convention is snake_case: lowercase words joined by underscores. Stick to it and your code looks like everyone else's, which is the point of a convention.

A good name says what the value is. n saves four keystrokes once and costs you ten seconds every time you read the line afterwards.

naming
RuleYesNo
snake_casewatering_dayswateringDays, WateringDays
Starts with a letter or underscoreplant_22nd_plant
No reserved wordslist_of_nameslist, str, if
Says what it holdstotal_pricetp, data, thing
Case mattersname and Nameare two different variables

The types

Five you will use constantly.

03 The five everyday types

type() tells you what you are holding. Reach for it the moment something behaves oddly — most confusing bugs are a value being a different type than you assumed.

A whole number written with a decimal point is a float: 5.0 is a float, 5 is an int. That matters because / always produces a float.

types
TypeExampleNotes
int42, -7, 0Whole numbers, no size limit
float3.14, 5.0Decimals. Slightly imprecise — see entry 9.
str"Ada", 'x'Text. Single or double quotes, pick one and keep to it.
boolTrue, FalseCapital T and F. Lowercase is a NameError.
list[1, 2, 3]An ordered, changeable collection

04 Converting between them

Python will not quietly turn text into a number for you. You convert on purpose, with a function named after the target type.

input() always returns a string, even when the user types digits. Forgetting to wrap it in int() is the single most common bug in a first Python program.

converting.py
int("42")       # 42
float("3.14")   # 3.14
str(42)         # "42"
bool(0)         # False

# The classic
age = input("Your age? ")      # "17" - a STRING
print(age + 1)                 # TypeError

age = int(input("Your age? ")) # 17 - an int
print(age + 1)                 # 18

# int() on something that is not a number raises ValueError
int("abc")      # ValueError: invalid literal for int()
int("3.9")      # ValueError too - use float() first
int(3.9)        # 3  - truncates, does not round

Strings

The type you will handle most.

05 Working with strings

Strings can be joined, repeated, measured and sliced. Index positions start at zero, and a negative index counts back from the end.

Strings are immutable: methods like .upper() return a new string rather than changing the original. name.upper() on its own line does nothing useful — you have to assign the result.

strings.py
name = "Ada Lovelace"

len(name)            # 12
name[0]              # "A"
name[-1]             # "e"   last character
name[0:3]            # "Ada" from 0 up to but not including 3
name.upper()         # "ADA LOVELACE"
name.lower()
name.strip()         # removes whitespace at both ends
name.replace("Ada", "Grace")
name.split(" ")      # ["Ada", "Lovelace"]
"Ada" in name        # True

"ab" + "cd"          # "abcd"
"-" * 20             # "--------------------"

06 f-strings

An f-string puts a value straight into text. Put f before the quote and wrap any expression in braces.

This replaces older approaches you may see in tutorials — joining with +, or .format(). Use f-strings; they are shorter and they do not break when a value is not a string.

f-strings.py
name = "Ada"
count = 3

print(f"{name} has {count} plants")

# Any expression fits in the braces
print(f"Next year: {count + 1}")
print(f"Shouted: {name.upper()}")

# Formatting numbers: 2 decimal places
price = 4.5
print(f"Total: ${price:.2f}")     # Total: $4.50

# Without the f, you get the braces literally
print("{name} has plants")        # {name} has plants

Where it goes wrong

Three traps, in the order you will hit them.

07 Mixing types

+ means add between two numbers and join between two strings. Between one of each it means nothing, and Python says so rather than guessing.

This is a deliberate design choice, and a good one. JavaScript guesses in the same situation and produces "51", which hides the bug instead of reporting it.

mixing.py
"5" + 1        # TypeError: can only concatenate str (not "int") to str
5 + 1          # 6
"5" + "1"      # "51"

# Fix by converting whichever side is wrong
int("5") + 1   # 6
"5" + str(1)   # "51"

# * does work between a string and an int
"ab" * 3       # "ababab"

# Comparisons across types do not
"10" > 9       # TypeError: '>' not supported between str and int

08 Division and remainder

Three operators that look similar and are not. / always gives a float, even when the division is exact.

% is how you test for even, odd, or “every nth time”. n % 2 == 0 means n is even.

division.py
7 / 2      # 3.5   true division, always a float
7 // 2     # 3     floor division, drops the remainder
7 % 2      # 1     the remainder itself
2 ** 10    # 1024  power

6 / 3      # 2.0   note the .0 - still a float

# Useful patterns
n % 2 == 0           # is n even?
total // count       # whole items per group
seconds % 60         # seconds left over after whole minutes

09 Floats are approximate

Not a Python bug. Computers store decimals in binary, and some everyday decimals have no exact binary form, exactly as a third has no exact decimal form.

Never compare two floats with ==. Compare the gap between them against a small tolerance, or use round() first.

floats.py
0.1 + 0.2              # 0.30000000000000004
0.1 + 0.2 == 0.3       # False  (!)

# Compare with a tolerance instead
abs((0.1 + 0.2) - 0.3) < 0.000001    # True

# Or round before comparing or displaying
round(0.1 + 0.2, 2)    # 0.3
f"{0.1 + 0.2:.2f}"     # "0.30"

# For money, work in whole pence and divide only when printing
total_pence = 1999
print(f"${total_pence / 100:.2f}")   # $19.99

10 Constants and None

Python has no way to stop a value being changed. The convention is an ALL_CAPS name, which tells other people not to reassign it.

None is a value meaning nothing here yet. It is not zero and not an empty string. Test for it with is, not ==.

constants.py
MAX_PLANTS = 50          # the convention for "do not change this"
SECONDS_PER_DAY = 86400

last_watered = None      # deliberately empty

if last_watered is None:
    print("never watered")

# A function with no return statement gives back None
result = print("hi")
print(result)            # None