Essay
Learning Python, Part 1: Values, Types and Talking to the Computer
Study notes on assignment, numbers, type conversion, input and output, and the three kinds of error, with invented examples. Written entirely by an AI model.
This is the first of six parts. It covers the ground floor of Python: what a variable is, how numbers behave, and how a program talks to the person running it. Each part ends with a pointer to somewhere to practise, including the Python Drills tool, where your code is checked in your browser.
Names and assignment
A statement like x = 5 does not say “x equals 5”. It says: work out the right-hand side, then attach the name on the left to the result. Because the right side is evaluated first, this is legal:
tea_cups = 3
tea_cups = tea_cups + 2 # 3 + 2 is worked out, then the name is re-attached
print(tea_cups) # 5
Python lets you assign several names in one statement, and evaluates everything on the right before touching anything on the left. That is why swapping needs no temporary variable:
left, right = "red", "blue"
left, right = right, left
print(left, right) # blue red
The shorthand forms +=, -=, *=, /=, //=, %= and **= update a name in place. tea_cups += 2 means tea_cups = tea_cups + 2.
Names are case sensitive, can contain letters, digits and underscores, cannot start with a digit, and cannot be a reserved word such as for or class.
Numbers and their operators
There are two everyday number types. An int is a whole number of any size, limited only by memory. A float is a number with a fractional part, stored approximately. A literal with a decimal point is a float, even 3.0.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * |
the usual | 2 + 3.0 |
5.0 |
/ |
true division, always a float | 8 / 2 |
4.0 |
// |
floor division, rounds towards negative infinity | -7 // 2 |
-4 |
% |
remainder, takes the sign of the divisor | -7 % 2 |
1 |
** |
power | 2 ** 10 |
1024 |
// and % come as a pair. If you are putting 47 eggs into cartons of 12, 47 // 12 is the 3 full cartons and 47 % 12 is the 11 left over. The two always satisfy a == (a // b) * b + a % b, which is a useful sanity check when negative numbers are involved.
Converting between types
int(6.8)is6. It chops off the fraction, soint(-3.9)is-3.round(6.8)is7. Python 3 rounds exact halves to the nearest even number, soround(2.5)is2andround(3.5)is4.float(6)is6.0.int("3.5")raises aValueError. Convert in two steps instead:int(float("3.5")).
Floats are approximations
Computers store floats in binary, and most decimal fractions have no exact binary form. The classic result:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
Never test floats for exact equality. Ask whether they are close enough:
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # True
Integers do not have this problem. 10 ** 25 + 1 is exact, while 10.0 ** 25 + 1 == 10.0 ** 25 is True because the + 1 is below the float’s precision. Choose int for counts and float only when you need fractions.
Talking to the user
print(a, b, c) writes its arguments separated by spaces and ends with a newline. Two keyword arguments change that:
print("lantern", "tea", sep=" | ") # lantern | tea
print("no newline", end="")
input(prompt) shows the prompt and returns what the user typed, always as a string, even if they typed digits. Convert before doing arithmetic:
bill = float(input("Bill total: "))
people = int(input("People: "))
print(f"Each person pays {bill / people:.2f}")
The f"..." string drops any expression into {} braces, and :.2f formats a float to two decimal places. Part 4 returns to formatting.
If the user types abc where a number is expected, float() raises a ValueError. Part 5 shows how to catch that and ask again.
Three kinds of error
| Kind | When you see it | Example |
|---|---|---|
| Syntax error | Before anything runs | total = (1 + 2 |
| Runtime error | Partway through, with a traceback | "tea" + 3 raises TypeError |
| Logic error | Never. The program runs and gives the wrong answer | using 2 ** 5 when you meant 2 * 5 |
A traceback reads from the bottom: the last line names the exception and says what went wrong, and the lines above show where. Logic errors are the hard ones, because only your tests can find them.
From problem to program
A reliable routine for anything bigger than a few lines:
- State what goes in and what comes out. For the bill splitter: a total and a head count in, an amount each out.
- Write the steps in plain words (pseudocode) before you write Python.
- Translate, one step at a time.
- Test a typical case, the edges (zero, one, the largest allowed) and invalid input.
Almost every small program is shaped like input, then process, then output. Naming the three parts makes it clear where a bug can hide.
Where to practise
Open the Scratchpad for a Python prompt, and try the integer and float examples above, especially the negative ones. The drills start with functions, so they fit from Part 3 onwards. Part 2 moves on to decisions and loops.