The essentials of module 01 on one page. Every runnable block on this page is checked against its output.
| I want to… |
Use… |
Example |
| start the interactive REPL |
python in a terminal |
python |
| leave the REPL |
exit(), or Ctrl+D (macOS, Linux), Ctrl+Z then Enter (Windows) |
exit() |
| run a script |
python file.py in the script’s folder |
python report.py |
| run a script, then keep exploring its variables |
python -i file.py |
python -i report.py |
| run one line from the terminal |
python -c "code" |
python -c "print(3 * 79.99)" |
| see a value in a script |
print() |
print(total) |
| check a type |
type(x) |
type(21.7) → <class 'float'> |
| turn text into a whole number |
int(text) |
int(" 42 ") → 42 |
| turn text into a decimal number |
float(text) |
float("21.7") → 21.7 |
| turn a number into text |
str(x) or an f-string |
str(1375) → '1375' |
| divide and drop the remainder |
// |
250 // 12 → 20 |
| get the remainder |
% |
250 % 12 → 10 |
| round for display |
round(x, n) or f"{x:.2f}" |
round(21.4333, 2) → 21.43 |
| compare two floats |
math.isclose(a, b) |
math.isclose(0.1 + 0.2, 0.3) → True |
| compare a float with 0 |
math.isclose(x, 0, abs_tol=1e-9) |
math.isclose(0.1 + 0.2 - 0.3, 0, abs_tol=1e-9) → True |
| check a range |
chained comparison |
19.0 <= t <= 23.0 |
| test for a missing value |
x is None |
reading is None |
| test a yes/no text answer |
compare the text |
answer == "yes" |
| join values into a sentence |
f-string |
f"{units} units" |
| print values without spaces between them |
sep="" |
print("S", 1, sep="") → S1 |
stay on the same line after print() |
end="" |
print("Loading", end="") |
| ask the user for text |
input("prompt") |
int(input("Qty: ")) |
| show a value with its quotes |
repr(x) |
repr(" 3 ") → "' 3 '" |
| debug-print a name and its value |
f"{x=}" |
f"{total=}" → total=458.94 |
| Command |
Does |
python |
Starts the REPL. The prompt >>> waits for one line. ... means “continue the statement”. |
python report.py |
Runs the script from top to bottom, then exits. |
python -i report.py |
Runs the script, then opens the REPL with its variables. |
python -c "print(2 ** 10)" |
Runs one line of code. |
python --version |
Shows the version, for example Python 3.13.7. |
python3 (macOS, Linux) / py (Windows) |
The command when no environment is active. |
|
REPL |
Script |
| Input |
one line at a time |
a .py file |
| Shows values |
echoes every expression (strings with quotes) |
only print() output (strings without quotes) |
Echoes None |
no |
— |
| Use for |
testing, exploring |
code to keep and rerun |
units_sold = 1375 # create: name = value
units_sold = units_sold + 25 # reassign: the right side runs first
units_sold += 100 # augmented assignment; also -=, *=, /=, //=, %=, **=
low, high = 19.0, 23.0 # assign two names in one line
print(units_sold, low, high)
| Rule or convention |
Good |
Bad |
letters, digits, _ only |
store_id |
store-id, store id |
| no digit first |
q1_sales |
1q_sales |
| case-sensitive |
total ≠ Total |
|
| no keywords |
class_label |
class, for, None |
| snake_case (PEP 8) |
monthly_charges |
MonthlyCharges, monthlycharges |
| say what it means, add the unit |
size_sqm, interval_minutes |
x, data2, temp |
| do not reuse built-in names |
lowest, highest |
min, max, sum, type |
| Type |
Literals |
Falsy value |
Convert with |
Typical data |
int |
3, -12, 20_228 |
0 |
int() |
counts, quantities, years |
float |
21.7, 79.99, 1e-3, 2.0 |
0.0 |
float() |
measurements, prices, rates |
bool |
True, False |
False |
bool() |
flags, results of comparisons |
str |
"S01", 'S01', "" |
"" |
str() |
ids, names, raw text from files |
NoneType |
None |
None |
— |
missing values |
>>> type(20_228), type(1e-3), type(None)
(<class 'int'>, <class 'float'>, <class 'NoneType'>)
| Op |
Name |
Example |
Result |
Result type |
+ |
add |
21.5 + 0.4 |
21.9 |
float if any float |
- |
subtract |
2850 - 1420 |
1430 |
|
* |
multiply |
3 * 249 |
747 |
|
/ |
divide |
10 / 4 |
2.5 |
always float |
// |
floor divide |
10 // 4 |
2 |
int for ints |
% |
modulo |
10 % 4 |
2 |
int for ints |
** |
power |
2 ** 10 |
1024 |
|
-x |
negate |
-(-4) |
4 |
|
units, box_size = 250, 12
full_boxes = units // box_size # 20 full boxes
left_over = units % box_size # 10 units in the last box
boxes = (units + box_size - 1) // box_size # ceiling division: 21 boxes in total
print(full_boxes, left_over, boxes, full_boxes * box_size + left_over == units)
print(7 // 2, -7 // 2, 7 % 3, -7 % 3) # // rounds toward minus infinity
print(divmod(555, 60)) # (hours, minutes) in one call
Precedence, from first to last (same row: left to right, except **, which runs right to left):
| Order |
Operators |
| 1 |
( ) |
| 2 |
** |
| 3 |
-x, +x |
| 4 |
*, /, //, % |
| 5 |
+, - |
| 6 |
==, !=, <, <=, >, >=, is, is not |
| 7 |
not |
| 8 |
and |
| 9 |
or |
print(21.0 + 21.9 + 21.4 / 3) # wrong average: only 21.4 is divided
print((21.0 + 21.9 + 21.4) / 3) # right
print(-2 ** 2, (-2) ** 2, 2 ** 3 ** 2) # ** before minus; ** is right to left
Number helpers:
| Call |
Result |
Note |
round(21.7) |
22 |
returns int |
round(21.4333, 2) |
21.43 |
returns float |
round(2.5), round(3.5) |
2, 4 |
halves go to the even number |
abs(-3.5) |
3.5 |
|
min(21.0, 19.8, 22.9) |
19.8 |
any number of arguments |
max(21.0, 19.8, 22.9) |
22.9 |
|
divmod(555, 60) |
(9, 15) |
(a // b, a % b) |
math.isclose(a, b) |
True/False |
needs import math; relative tolerance |
math.isclose(x, 0, abs_tol=1e-9) |
True/False |
near 0, add an absolute tolerance |
print(0.1 + 0.2, 0.1 + 0.2 == 0.3) # binary floats are approximate
print(round(0.1 + 0.2, 2), math.isclose(0.1 + 0.2, 0.3)) # display / compare
print(math.isclose(0.1 + 0.2 - 0.3, 0), math.isclose(0.1 + 0.2 - 0.3, 0, abs_tol=1e-9))
print(79.99 + 14.99, f"{79.99 + 14.99:.2f}") # format money for display
print(7999 + 1499) # exact: money in whole cents
0.30000000000000004 False
| Task |
Use |
Avoid |
| show a value |
f"{x:.2f}" or round(x, 2) |
printing raw floats in reports |
| compare two computed floats |
math.isclose(a, b) |
a == b |
| compare a computed float with 0 |
math.isclose(x, 0, abs_tol=1e-9) |
math.isclose(x, 0) (always False unless x is exactly 0) |
| compare to the cent |
round(a, 2) == round(b, 2) |
|
| exact money arithmetic |
whole cents (int) or decimal.Decimal |
floats in an accounting system |
| Op |
Meaning |
Example |
Result |
==, != |
equal, not equal |
"S01" == "s01" |
False (case matters) |
<, <=, >, >= |
order |
6 <= 6 |
True |
a <= x <= b |
chained: a <= x and x <= b |
19.0 <= 23.0 <= 23.0 |
True |
is, is not |
same object (use with None) |
x is None |
|
and |
both |
True and False |
False |
or |
at least one |
False or True |
True |
not |
opposite |
not 0 |
True |
tenure_months, logins_last_30d, contract = 4, 2, "month-to-month"
at_risk = tenure_months <= 6 and logins_last_30d <= 3
high_risk = contract == "month-to-month" and (support_tickets >= 3 or at_risk)
print(at_risk, high_risk, not at_risk)
print(logins_last_30d == 1 or logins_last_30d == 2) # write both comparisons in full
Falsy (acts as False) |
Truthy (acts as True) |
False, None |
True |
0, 0.0 |
any other number, negatives too: -1.5 |
"" (empty string) |
any non-empty string: " ", "0", "False", "no" |
print(bool(0), bool(""), bool(None), bool(" "), bool("0"), bool("no"))
print(bool(answer), answer == "yes") # bool() does not read the words
False False False True True True
reading = None # the sensor sent nothing
print(reading, reading is None, reading is not None, reading == 0)
None means “unknown” or “not set”. 0 is a real value.
- Test it with
is None / is not None (PEP 8, ruff rule E711).
- Arithmetic on
None raises TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'.
- A function with no
return value gives back None (module 05).
| Call |
Result |
Note |
int("1375") |
1375 |
|
int(" 42\n") |
42 |
surrounding whitespace is ignored |
int("1_375") |
1375 |
underscores between digits are allowed |
int("21.7") |
ValueError |
whole-number text only |
int(float("21.7")) |
21 |
two steps |
int(21.7), int(-21.7) |
21, -21 |
truncates toward zero |
round(21.7) |
22 |
nearest |
float("21.7"), float("1e-3") |
21.7, 0.001 |
|
float("nan") |
nan |
“not a number”, a float |
float("n/a"), float("") |
ValueError |
|
str(79.99), str(None) |
'79.99', 'None' |
|
int(True), float(False) |
1, 0.0 |
|
bool(0), bool("0") |
False, True |
truthiness, not meaning |
print(int(float("21.7")), round(float("21.7")))
ValueError: could not convert string to float: 'n/a'
| Implicit conversion |
Example |
Result |
int with float → float |
2 * 1.5 |
3.0 |
bool in arithmetic → int |
4.99 * True |
4.99 |
str with a number |
"3" + 4 |
TypeError (never automatic) |
str times int → repeat |
"-" * 5 |
'-----' |
store, total = "S01", 458.94
print("Store", store, "total:", total) # arguments joined by spaces
print("2024", "05", "01", sep="-") # custom separator
print("Loading...", end=" ") # no line break at the end
print(f"{store}: {total:.1f} USD") # f-string with a format spec
f-string basics (module 02 covers format specs in full):
| Spec |
Value |
Shows |
Use |
{x} |
21.7 |
21.7 |
plain value |
{x:.2f} |
634.9499999999999 |
634.95 |
fixed decimals |
{x:,} |
20228 |
20,228 |
thousands separator |
{x:,.2f} |
109986.25 |
109,986.25 |
money |
{x:02d} |
7 |
07 |
clock times, dates |
{x:+.1f} |
1.3 |
+1.3 |
always show the sign |
{x:.1%} |
0.1926 |
19.3% |
rates as percentages |
{x=} |
total = 458.94 |
total=458.94 |
quick debugging |
print(f"Churn: {churn_rate:.1%} Time: {hour:02d}:{minute:02d} {total=}")
Churn: 19.3% Time: 07:05 total=458.94
name = input("Sensor id: ") # always returns str
quantity = int(input("Quantity: ")) # convert at once for numbers
price = float(input("Unit price: "))
confirm = input("Save? (yes/no) ") == "yes" # compare text; never bool(text)
| Fact |
Detail |
| Return type |
always str, without the final line break |
| Empty reply |
""; int("") raises ValueError |
| Tests and pipelines |
avoid input(); use files or command-line arguments (module 08) |
| Form |
Example |
Use |
| full-line comment |
# Valid range from the sensor data sheet. |
explain why, give sources and units |
| inline comment |
x = 0.35 # °C per day |
two spaces before #, one after |
| switch a line off |
# print(debug_value) |
Ctrl+/ (Cmd+/ on macOS) in most editors |
| docstring |
"""Return the mean.""" |
documents a function (module 05) |
| Error (last traceback line) |
Typical cause |
Fix |
NameError: name 'x' is not defined |
typo, or used before assignment |
fix the name; assign first |
TypeError: can only concatenate str (not "int") to str |
"Units: " + 5 |
f-string or str(5) |
TypeError: can't multiply sequence by non-int of type 'float' |
text from input() times a price |
int() or float() first |
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' |
arithmetic on None |
test is None first |
ValueError: invalid literal for int() with base 10: '21.7' |
int() on decimal text |
float(), or int(float(...)) |
ValueError: could not convert string to float: 'error' |
text that is not a number |
clean or skip the value (module 06) |
ZeroDivisionError: division by zero |
dividing by a count of 0 |
check the count first (module 03) |
SyntaxError: invalid syntax |
a terminal command typed at >>>; with = where == belongs, Python adds a hint |
leave the REPL first; use == to compare |
- A script does not echo values. A bare
total line prints nothing.
input() and every line of a text file give str. Convert before you calculate.
/ always returns a float: 10 / 2 is 5.0.
-7 // 2 is -4. // rounds toward minus infinity, int() truncates toward zero.
0.1 + 0.2 != 0.3. Compare floats with math.isclose(); near 0, add abs_tol=1e-9.
-7 % 3 is 2: the result of % has the sign of the divisor.
- Keep ids as
str: int("00042") is 42, and the leading zeros are lost.
round(2.5) is 2. Halves round to the even number.
-2 ** 2 is -4. Use (-2) ** 2.
a + b + c / 3 is not an average. Write (a + b + c) / 3.
bool("False"), bool("0") and bool("no") are all True. Compare the text instead.
x == 1 or 2 is always truthy. Write x == 1 or x == 2.
None is not 0. Test it with is None.
True, False and None need a capital letter.
- Naming a variable
min, max, sum or type hides the built-in function with that name.
= assigns; == compares.