01. Python basics
This module is your first contact with Python. You run code, store values, calculate with them and print the results. Every example uses the kind of data you analyze later in the course: sensor readings, sales figures and customer records.
What you will learn
Section titled “What you will learn”- Run Python code in the interactive REPL and as a script file.
- Store values in variables and give them clear names.
- Use the five basic types (
int,float,bool,strandNone) and check a type withtype(). - Calculate with arithmetic, comparison and logical operators, including floor division (
//) and modulo (%). - Convert values from one type to another and read the error when a conversion fails.
- Print clear output, read text with
input()and explain your code with comments.
Prerequisites
Section titled “Prerequisites”- Python 3.12 or newer: Install Python.
- A project folder with an active environment: Virtual environments.
- You can open a terminal and run a file: Running code.
- The course datasets in a
data/folder inside your project: Get the data.
You need no programming experience. This is the first module.
Concepts
Section titled “Concepts”Programs, source code and the interpreter
Section titled “Programs, source code and the interpreter”A program is a list of instructions for a computer. You write the instructions as text. This text is the source code (or just code). Python source code is plain text, saved in files whose names end in .py.
The computer cannot run Python text directly. A program called the interpreter reads your code and carries out each instruction. When you install Python, you install the interpreter. The command python starts it.
Two more words appear on every page of this course:
- A statement is one complete instruction, usually one line, such as
total = 120 + 80. - An expression is a piece of code that produces a value, such as
120 + 80.
You give code to the interpreter in one of two ways: one line at a time in the REPL, or a whole file as a script.
flowchart LR
S["Script file<br/>report.py"] --> I["Python interpreter"]
R["One line typed<br/>in the REPL"] --> I
I --> O["Output<br/>in the terminal"]
The REPL: try one line at a time
Section titled “The REPL: try one line at a time”The REPL (Read–Eval–Print Loop) is an interactive Python session. It reads the line you type, evaluates it (works out its value), prints the result and waits for the next line. The REPL is the fastest way to test an idea: a formula, a conversion or a function you have not used before.
Open a terminal, activate your environment and type python. The REPL shows a version banner and the prompt >>>, which means “Python is waiting for you”.
python # start the REPL (use python3 if no environment is active)To leave the REPL, type exit() or press Ctrl+D.
python # start the REPL (use py if no environment is active)To leave the REPL, type exit() or press Ctrl+Z, then Enter.
Here is a short session. You type the text after >>> . The other lines are Python’s answers.
>>> 21.5 + 0.421.9>>> 2850 - 14201430>>> "sensor" + "-01"'sensor-01'The REPL shows text with quotes, so you can see that 'sensor-01' is text and not a number. In this course, every block with >>> prompts is a REPL session.
Scripts: save code in a file
Section titled “Scripts: save code in a file”A script is a .py file that the interpreter runs from the first line to the last. Use a script for code that you want to keep, run again or share. Real work runs as scripts: data pipelines, reports and scheduled jobs.
Create a file hello.py in your project folder with this content. The Output block under it shows what the script prints.
# hello.py: your first Python script.print("Hello from a script!")print("Python is ready for data work.")Hello from a script!Python is ready for data work.Run it from a terminal that is open in the same folder:
python hello.pyprint() is a function: a named piece of code that does one job. You call a function with its name and parentheses. A value inside the parentheses is an argument. print() writes its arguments to the terminal as one line. The first line of the file starts with #, so it is a comment, and Python ignores it (see Comments).
| REPL | Script | |
|---|---|---|
| What you give Python | one line at a time | a whole .py file |
| Shows values | automatically, after each expression | only what you pass to print() |
| Kept when you close it | no | yes, the file stays |
| Best for | quick tests, exploring a value | code to keep, rerun and share |
Variables: names for values
Section titled “Variables: names for values”A value is one piece of data, such as 21.7 or "S1". A variable is a name that refers to a value. You create a variable with an assignment: a name, the = sign and a value.
temperature = 21.7sensor_id = "S1"print(sensor_id, temperature)S1 21.7The = sign means “make this name refer to this value”. It is not the equals sign of mathematics. Read temperature = 21.7 as “temperature gets 21.7”.
You can give a name a new value at any time. The old value is then forgotten:
temperature = 22.1temperature = temperature + 0.5print(temperature)22.6Python works out the right side first (22.1 + 0.5). Then the name temperature gets the result. The short form temperature += 0.5 does the same thing. It is called augmented assignment. The forms -=, *= and /= also exist.
Names follow four rules:
| Rule | Valid | Invalid |
|---|---|---|
Only letters, digits and _ |
store_id |
store-id |
| Must not start with a digit | sales_2024 |
2024_sales |
| Upper and lower case are different | total and Total are two names |
|
| Must not be a keyword | class_label |
class |
A keyword is a word that Python reserves for its own grammar, such as if, for, class, True and None.
The Python style guide, PEP 8, says: write variable names in snake_case, which means lowercase words joined by underscores, such as monthly_charges or units_sold. Choose names that say what the value means. unit_price tells the reader more than p or x.
Reading an error message
Section titled “Reading an error message”When Python cannot run a line, it stops and raises an exception: an error with a type and a message. It prints a traceback, a report that shows where the error happened. Read the last line first. It names the error type and explains the problem.
>>> revenue = 79.99>>> print(units_sold)Traceback (most recent call last): File "<python-input-1>", line 1, in <module>NameError: name 'units_sold' is not definedPython 3.12 shows File "<stdin>" instead of File "<python-input-1>". The last line is the same in every version.
NameError means that Python does not know the name. Here, no line has assigned a value to units_sold yet. A typo is the other common cause. When the unknown name is close to a known one, Python adds a hint. For print(revenu), the last line is NameError: name 'revenu' is not defined. Did you mean: 'revenue'?.
You will meet four error types in this module:
| Error | Meaning | Typical cause |
|---|---|---|
NameError |
unknown name | a typo, or a variable used before it is assigned |
TypeError |
wrong type for this operation | "3" + 4 (text plus a number) |
ValueError |
right type, unusable value | int("n/a") |
ZeroDivisionError |
division by zero | total / order_count when order_count is 0 |
Module 06 teaches you to handle errors so that a program can continue.
The basic types
Section titled “The basic types”Every value has a type. The type decides what you can do with the value: you can divide two numbers, but you cannot divide two words. Five types appear in almost every script:
| Type | Holds | Examples | Data use |
|---|---|---|---|
int |
whole numbers (integers) | 3, -12, 20_228 |
counts: orders, units sold, rows |
float |
numbers with a decimal point | 21.7, 79.99, 1e-3 |
measurements, prices, rates |
bool |
truth values (Booleans) | True, False |
flags: churned, has autopay, valid |
str |
text (strings) | "S01", 'Chicago' |
ids, names, categories, raw lines of a file |
NoneType |
only the value None |
None |
a missing value |
The built-in function type() tells you the type of a value. A built-in function is a function that Python always provides, with no setup.
>>> type(1375)<class 'int'>>>> type(79.99)<class 'float'>>>> type(True)<class 'bool'>>>> type("Wireless Earbuds")<class 'str'>>>> type(None)<class 'NoneType'>Some details about each type:
- A literal is a value written directly in the code.
"S01"is a string literal and79.99is a float literal. - Single quotes and double quotes make the same string:
'S01' == "S01". - Underscores in a number literal only help you read it.
20_228is the integer 20228. 1e-3is scientific notation (a number times a power of 10) for 0.001. It is a float.\ninside a string is an escape sequence: a backslash code for one special character.\nis the line break at the end of each line of a text file."21.7"in quotes is astr, not a number. Data from files, forms and the web arrives as text. You convert it before you calculate.True,FalseandNonestart with a capital letter.truegives aNameError.
Arithmetic operators
Section titled “Arithmetic operators”An operator is a symbol that combines values, such as +. The values it combines are its operands.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 21.5 + 0.4 |
21.9 |
- |
subtraction | 2850 - 1420 |
1430 |
* |
multiplication | 4 * 249 |
996 |
/ |
division | 250 / 12 |
20.833333333333332 |
// |
floor division | 250 // 12 |
20 |
% |
modulo (remainder) | 250 % 12 |
10 |
** |
exponent (power) | 2 ** 10 |
1024 |
/always gives a float, even when the division is exact:10 / 2is5.0.- Floor division
//divides and then rounds down to a whole number. 250 units fill250 // 12= 20 full boxes of 12. - Modulo
%gives the remainder of the division. The last box has250 % 12= 10 units. - For any whole numbers
aandb(withbnot 0),(a // b) * b + a % bequalsa. - “Rounds down” means toward minus infinity. So
-7 // 2is-4, not-3. - When you mix an
intand afloat, the result is afloat:2 * 1.5is3.0.
>>> 10 / 25.0>>> 250 // 1220>>> 250 % 1210>>> -7 // 2-4>>> 120 / 0Traceback (most recent call last): File "<python-input-4>", line 1, in <module>ZeroDivisionError: division by zeroPrecedence is the order in which Python applies operators. It follows the rules of school mathematics:
| Order | Operators |
|---|---|
| 1 (first) | ( ) parentheses |
| 2 | ** |
| 3 | -x (negation) |
| 4 | *, /, //, % |
| 5 | +, - |
| 6 | comparisons: ==, !=, <, <=, >, >= |
| 7 | not |
| 8 | and |
| 9 (last) | or |
Operators of the same order run from left to right. There are two exceptions: ** runs from right to left, and comparisons chain (see Comparison and logical operators). When you are not sure, add parentheses. They cost nothing and show your intent.
>>> 21.0 + 21.9 + 21.4 / 350.03333333333333>>> (21.0 + 21.9 + 21.4) / 321.433333333333334>>> -2 ** 2-4>>> (-2) ** 24The first line divides only 21.4 by 3. The parentheses in the second line make Python add first, which gives the real average.
Four more built-in functions work with numbers:
| Function | What it does | Example | Result |
|---|---|---|---|
round(x) |
nearest whole number | round(21.7) |
22 |
round(x, n) |
round to n decimal places |
round(21.4333, 2) |
21.43 |
abs(x) |
distance from zero | abs(-3.5) |
3.5 |
min(a, b, ...) |
smallest argument | min(21.0, 19.8, 22.9) |
19.8 |
max(a, b, ...) |
largest argument | max(21.0, 19.8, 22.9) |
22.9 |
The value that a function gives back is its return value. round(21.7) returns 22.
Float precision
Section titled “Float precision”A computer stores a float in binary with a fixed number of digits (about 15 to 17 significant digits). Most decimal fractions, such as 0.1, have no exact binary form. Python stores the nearest value it can. So small errors appear:
>>> 0.1 + 0.20.30000000000000004>>> 3 * 79.99239.96999999999997>>> 0.1 + 0.2 == 0.3False>>> round(0.1 + 0.2, 2)0.3>>> import math>>> math.isclose(0.1 + 0.2, 0.3)TrueThis is not a bug in Python. Excel, JavaScript and NumPy store floats in the same standard format (IEEE 754), so they have the same tiny errors. Three rules keep you safe:
- Round only for display, with
round(x, 2)or an f-string (see Output). Keep the full value for further calculations. - Do not compare floats with
==. Usemath.isclose(a, b). It accepts a small relative difference, so to compare with 0, also pass an absolute tolerance:math.isclose(x, 0, abs_tol=1e-9). The lineimport mathloads themathmodule, a file of extra tools that comes with Python. Module 08 explains imports. Module 09 toursmath. round()rounds a value that is exactly halfway to the nearest even number:round(2.5)is2andround(3.5)is4. This rule (“round half to even”) avoids an upward bias when you round many values. Decimal halves such as 2.675 are not stored exactly (the stored value is 2.67499…), soround(2.675, 2)gives2.67.
Comparison and logical operators
Section titled “Comparison and logical operators”A comparison operator compares two values and gives a bool:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to | "S01" == "S01" |
True |
!= |
not equal to | 4 != 4 |
False |
< |
less than | 19.3 < 20.0 |
True |
<= |
less than or equal to | 6 <= 6 |
True |
> |
greater than | 868 > 2220 |
False |
>= |
greater than or equal to | 0.2 >= 0.15 |
True |
Do not confuse the two signs. = assigns a value to a name. == asks a question and gives True or False.
You can chain comparisons. 19.0 <= reading <= 23.0 means “reading is between 19.0 and 23.0, inclusive”. This is the clearest way to write a range check.
A logical operator combines bool values:
| Operator | Gives True when |
Example | Result |
|---|---|---|---|
and |
both sides are True |
True and False |
False |
or |
at least one side is True |
True or False |
True |
not |
the value is False |
not True |
False |
With operands that are not bool, and and or return one of the operands, not True or False: 0 or 5 is 5. Module 03 uses this behavior.
>>> reading = 22.9>>> 19.0 <= reading <= 23.0True>>> tenure_months = 4>>> logins_last_30d = 12>>> tenure_months <= 6 and logins_last_30d <= 3False>>> tenure_months <= 6 or logins_last_30d <= 3TrueTruthiness basics
Section titled “Truthiness basics”Python can treat any value as true or false. This idea is called truthiness. A value that counts as false is falsy. The falsy values of this module are False, 0, 0.0, "" (the empty string) and None. Almost every other value is truthy. The function bool() shows how Python sees a value:
>>> bool(0)False>>> bool(0.0)False>>> bool("")False>>> bool(None)False>>> bool(21.7)True>>> bool("0")True>>> bool("False")TrueThe strings "0" and "False" are truthy because they are not empty. Python does not read the words inside a string. Module 03 uses truthiness in if statements.
None: the missing value
Section titled “None: the missing value”None means “there is no value here”. Use it for a reading that a sensor did not send, a discount that is not known yet or a result that you have not computed. None is not the same as 0. A reading of 0 °C is a real temperature. A reading of None means that you do not know the temperature.
Test for None with the operator is:
>>> reading = None>>> reading>>> print(reading)None>>> reading is NoneTrue>>> reading == 0False>>> reading + 1Traceback (most recent call last): File "<python-input-5>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'The REPL shows nothing for a bare reading, because it never echoes None. print() shows it. An object is one value stored in memory; every value in Python is an object. The operator is checks if two names refer to the very same object. Only one None object exists, so is None is the reliable test, and PEP 8 recommends it.
Type conversion
Section titled “Type conversion”Type conversion (also called casting) makes a value of one type from a value of another type. To convert, call the name of the target type as a function:
| Call | Result | Note |
|---|---|---|
int("1375") |
1375 |
text to whole number |
float("21.7") |
21.7 |
text to decimal number |
int(" 42 ") |
42 |
spaces around the digits are ignored |
int(21.7) |
21 |
drops the decimals (truncates toward zero) |
round(21.7) |
22 |
rounds to the nearest whole number |
float(3) |
3.0 |
|
str(79.99) |
'79.99' |
number to text |
int(True) |
1 |
True counts as 1, False as 0 |
bool(0) |
False |
see Truthiness |
int("21.7") |
ValueError |
int() needs whole-number text |
float("n/a") |
ValueError |
the text is not a number |
A failed conversion raises a ValueError:
raw = "21.7"print(int(raw))ValueError: invalid literal for int() with base 10: '21.7'To turn the text "21.7" into the whole number 21, convert in two steps: int(float("21.7")).
Python converts some types for you. An int mixed with a float becomes a float. A bool in arithmetic counts as 1 or 0, so True + True is 2. Python never converts text to a number for you:
quantity = "3"print(quantity + 4)TypeError: can only concatenate str (not "int") to strPython stops because + with a string means “join two strings”. To concatenate means to join strings end to end. Convert first: int(quantity) + 4 gives 7, and quantity + str(4) gives "34".
Output with print() and f-strings
Section titled “Output with print() and f-strings”print() accepts any number of arguments. It writes them on one line, separated by spaces, and ends the line. Two keyword arguments (arguments passed with a name) change this: sep sets the separator and end sets what comes at the end.
store = "S01"total = 458.94print("Store", store, "total:", total)print("2024", "05", "01", sep="-")print("Loading readings...", end=" ")print("done")Store S01 total: 458.942024-05-01Loading readings... doneAn f-string is a string literal with the letter f before the opening quote. Python replaces each expression in curly braces, such as {units}, with its value. After the expression, a colon starts a format spec, a short code that controls how the value looks. :.2f shows exactly 2 decimals, and :, adds thousands separators.
product = "Wireless Earbuds"units = 1375unit_price = 79.99revenue = units * unit_priceprint(f"{product}: {units} units, revenue {revenue}")print(f"{product}: {units:,} units, revenue {revenue:,.2f} USD")Wireless Earbuds: 1375 units, revenue 109986.25Wireless Earbuds: 1,375 units, revenue 109,986.25 USDModule 02 covers f-strings and format specs in depth.
Input with input()
Section titled “Input with input()”input() shows a message, waits for the user to type a line and press Enter, and returns that line. The return value is always a str, even when the user types digits. Code that waits for a person cannot run on this page, so this block is for reading only:
quantity_text = input("Units to order: ")quantity = int(quantity_text)print("Order total:", quantity * 79.99)To see what happens, replace input() with the string it would return:
quantity_text = "3" # what input() returns when the user types 3print(type(quantity_text))quantity = int(quantity_text)print(type(quantity), quantity * 79.99)<class 'str'><class 'int'> 239.96999999999997Data analysis rarely uses input(), because the data comes from files and databases. You meet it in small command-line tools and in scripts that ask for a confirmation. Module 08 shows command-line arguments, the better way to give a script its settings.
Comments
Section titled “Comments”A comment is text that Python ignores. It starts with # and runs to the end of the line. Comments are for people. Explain why the code does something. The code already shows what it does.
# Sensor S3 drifts upward by about 0.35 °C per day, so subtract one day of drift.daily_drift = 0.35raw_reading = 22.9corrected = raw_reading - daily_drift # still a floatprint(round(corrected, 2))22.55A comment such as x = x + 1 # add 1 to x adds nothing. A good comment gives a reason, a unit or a source. You can also put # in front of a line to switch it off for a moment. Most editors do this with Ctrl+/ (Cmd+/ on macOS). Module 05 adds docstrings, the comments that document a function.
Worked examples
Section titled “Worked examples”Example 1 — Turn a REPL experiment into a report script
Section titled “Example 1 — Turn a REPL experiment into a report script”Goal: Summarize three orders from store S01 (Chicago) in a daily report that you can run again tomorrow.
Step 1 — Test the calculation in the REPL
Section titled “Step 1 — Test the calculation in the REPL”>>> order_1 = 79.99>>> order_2 = 249.00>>> order_3 = 129.95>>> order_1 + order_2 + order_3458.94>>> (order_1 + order_2 + order_3) / 3152.98The REPL echoes each result, so you check the numbers before you write the script. The order values are real product prices from data/products.csv.
Step 2 — Save the calculation as a script
Section titled “Step 2 — Save the calculation as a script”# report.py: summarize today's orders for store S01 (Chicago).# Each value is the revenue of one order, in USD.order_1 = 79.99order_2 = 249.00order_3 = 129.95order_count = 3
total = order_1 + order_2 + order_3average = total / order_count
print("Store S01 daily report")print("Orders:", order_count)print("Total revenue:", round(total, 2))print("Average order:", round(average, 2))Store S01 daily reportOrders: 3Total revenue: 458.94Average order: 152.98The script stores each intermediate result in a named variable, so a reader sees what each number means. The count is a variable too: total / order_count explains itself, and total / 3 does not.
Step 3 — Run the script from the terminal
Section titled “Step 3 — Run the script from the terminal”python report.pyStore S01 daily reportOrders: 3Total revenue: 458.94Average order: 152.98This is the exact command and output in your terminal. The terminal must be open in the folder that holds report.py. Tomorrow you change the order values and run the same command again.
Common mistakes:
- Leaving bare expressions such as
totalin the script. They print nothing. Useprint(total). - Typing
python report.pyat the>>>prompt. That is a terminal command, not Python code, so the REPL gives aSyntaxError. Leave the REPL first withexit(). - Running the command from another folder. Python then says
can't open file ... No such file or directory. Change to the project folder withcdfirst.
Example 2 — Convert a raw sensor reading
Section titled “Example 2 — Convert a raw sensor reading”Goal: Line 4 of data/readings.txt holds the temperature 21.7 as text. Turn it into a number, convert it to Fahrenheit and see what happens with the broken line 12, which holds error.
Step 1 — Inspect the raw value
Section titled “Step 1 — Inspect the raw value”raw = "21.7"print(raw, type(raw))print(raw + raw)21.7 <class 'str'>21.721.7A line read from a file is a str. print() shows it without quotes, so it looks like a number. The + proves it is text: it joins the two strings instead of adding them.
Step 2 — Convert the text to a float
Section titled “Step 2 — Convert the text to a float”celsius = float(raw)print(celsius, type(celsius))print(celsius + celsius)21.7 <class 'float'>43.4float() reads the text and returns a number. Now + adds. Keep the raw text and the number in two variables with different names, so you always know which one you have.
Step 3 — Convert to Fahrenheit
Section titled “Step 3 — Convert to Fahrenheit”fahrenheit = celsius * 9 / 5 + 32print(fahrenheit)print(round(fahrenheit, 1))71.0671.1The formula is °F = °C × 9 / 5 + 32. Precedence does the right thing here: * and / run before +. Round only when you show the value.
Step 4 — Try the broken line
Section titled “Step 4 — Try the broken line”bad_raw = "error"print(float(bad_raw))ValueError: could not convert string to float: 'error'float() cannot read the word error, so it raises a ValueError. Real files contain lines like this: module 06 catches the error and skips the line, and module 07 reads the whole file.
Common mistakes:
- Calling
int("21.7"). It raises aValueErrorbecauseint()accepts only whole-number text. Usefloat(). - Doing arithmetic before the conversion.
"21.7" * 2gives"21.721.7", and"21.7" + 1raises aTypeError. - Rounding too early. Round once, at the end, for display.
Example 3 — Turn a reading number into a day and time
Section titled “Example 3 — Turn a reading number into a day and time”Goal: Each sensor in data/sensors.csv logs a reading every 10 minutes, starting at 2024-05-01 00:00. Reading number 0 is at midnight. Find the date and clock time of reading number 1000.
Step 1 — Convert the reading number to minutes
Section titled “Step 1 — Convert the reading number to minutes”reading_number = 1000interval_minutes = 10minutes = reading_number * interval_minutesprint(minutes)10000Reading 1000 comes 10,000 minutes after the first reading. All values are int, so the result is an int.
Step 2 — Split the minutes into days
Section titled “Step 2 — Split the minutes into days”minutes_per_day = 24 * 60days = minutes // minutes_per_dayminutes_left = minutes % minutes_per_dayprint(days, minutes_left)6 1360A day has 1,440 minutes. // counts the full days (6). % gives the minutes that remain after those full days (1,360).
Step 3 — Split the remaining minutes into hours
Section titled “Step 3 — Split the remaining minutes into hours”hours = minutes_left // 60mins = minutes_left % 60day_of_month = 1 + daysprint(f"2024-05-{day_of_month:02d} {hours:02d}:{mins:02d}")2024-05-07 22:40The same // and % pair splits 1,360 minutes into 22 hours and 40 minutes. The format spec :02d shows a whole number with at least 2 digits, padded with a zero, so 7 becomes 07. Six full days after May 1 is May 7.
Step 4 — Check the result
Section titled “Step 4 — Check the result”rebuilt = days * minutes_per_day + hours * 60 + minsprint(rebuilt, rebuilt == minutes)10000 TrueRebuilding the input from the parts is a quick test of your arithmetic. If you had used / anywhere, the parts would be floats and the check would show it.
Common mistakes:
- Using
/instead of//.10000 / 1440is6.944444444444445, which is not a number of days you can show on a clock. - Forgetting that reading 0 is at midnight. Reading 1 is at 00:10, not reading 0.
- Splitting minutes with
// 100and% 100instead of 60. An hour has 60 minutes, not 100.
Example 4 — Price an order line with a discount
Section titled “Example 4 — Price an order line with a discount”Goal: Compute the revenue for one line of a sales file: 3 Noise-Cancelling Headphones at 249.00 USD each, with a 10% discount. data/sales.csv computes each line as revenue = quantity × unit price × (1 − discount), rounded to 2 decimals.
Step 1 — Store the inputs
Section titled “Step 1 — Store the inputs”quantity = 3unit_price = 249.00discount = 0.1print(type(quantity), type(unit_price), type(discount))<class 'int'> <class 'float'> <class 'float'>The quantity is a count, so it is an int. The price and the discount rate are float values. Store the discount as a fraction (0.1), not as a percentage (10).
Step 2 — Write the formula with parentheses
Section titled “Step 2 — Write the formula with parentheses”wrong = quantity * unit_price * 1 - discountrevenue = quantity * unit_price * (1 - discount)print(wrong)print(revenue)746.9672.3000000000001Without parentheses, Python multiplies first and then subtracts 0.1 from 747.0. The parentheses make Python compute 1 - discount (0.9) first. The second result shows a float precision error: the exact answer is 672.3.
Step 3 — Round the result for the report
Section titled “Step 3 — Round the result for the report”print("Revenue:", round(revenue, 2))print(f"Revenue: {revenue:.2f} USD")Revenue: 672.3Revenue: 672.30 USDround(revenue, 2) returns the new number 672.3, and a float does not keep trailing zeros. The f-string spec :.2f always shows 2 decimals, which suits money. Neither one changes revenue.
Step 4 — Compare floats safely
Section titled “Step 4 — Compare floats safely”import math
print(revenue == 672.3)print(math.isclose(revenue, 672.3))FalseTrue== says False because of the tiny error in the last digit. math.isclose() says True because the two values agree to about 9 significant digits. Use it whenever you compare two computed floats (with abs_tol when one side is 0).
Common mistakes:
- Writing the discount as
10instead of0.1. The result is negative:3 * 249.00 * (1 - 10)is-6723.0. - Leaving out the parentheses around
1 - discount. - Comparing money with
==. Usemath.isclose(), or compare rounded values:round(revenue, 2) == 672.3.
Example 5 — Flag a customer at risk of churning
Section titled “Example 5 — Flag a customer at risk of churning”Goal: Churn means that a customer cancels the subscription. In data/customers.csv, customers with 1 to 6 months of tenure churn 44% of the time, and customers with 3 logins or fewer in 30 days churn 43% of the time. Flag a customer who matches both rules.
Step 1 — Store the record in variables
Section titled “Step 1 — Store the record in variables”customer_id = "C03991"tenure_months = 6logins_last_30d = 2has_autopay = 0avg_session_minutes = None # the file says 6.4; None simulates a gapprint(customer_id, tenure_months, logins_last_30d, has_autopay, avg_session_minutes)C03991 6 2 0 NoneThese are the real values of customer C03991, typed by hand. has_autopay is stored as 0 or 1, as in the file. The file has no gaps in avg_session_minutes, so this example sets it to None to show how to handle one.
Step 2 — Compare each field
Section titled “Step 2 — Compare each field”short_tenure = tenure_months <= 6low_logins = logins_last_30d <= 3print(short_tenure, low_logins)True TrueEach comparison gives a bool. Storing it in a well-named variable turns a rule into a readable word.
Step 3 — Combine the rules with and and or
Section titled “Step 3 — Combine the rules with and and or”at_risk = short_tenure and low_loginswatch_list = short_tenure or low_loginsprint("At risk:", at_risk)print("Watch list:", watch_list)print("Autopay:", bool(has_autopay))At risk: TrueWatch list: TrueAutopay: Falseand needs both rules. or needs one. bool(has_autopay) turns the stored 0 into False, because 0 is falsy.
Step 4 — Handle the missing value
Section titled “Step 4 — Handle the missing value”print("Session data missing:", avg_session_minutes is None)Session data missing: Trueis None reports the missing value without crashing. Arithmetic on the missing value does crash:
print(avg_session_minutes * 2)TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'Module 03 uses the is None test in an if statement to choose what to do.
Common mistakes:
- Writing
logins_last_30d <= 3 or 5. Python reads this as(logins_last_30d <= 3) or 5, and5is truthy, so the result is neverFalse. Write each comparison in full. - Testing
avg_session_minutes == None. It works forNone, but PEP 8 asks foris None, which cannot be fooled by unusual objects. - Treating a missing value as 0. A session time of 0 minutes and an unknown session time mean different things.
Example 6 — Read and confirm an order from the keyboard
Section titled “Example 6 — Read and confirm an order from the keyboard”Goal: A small checkout script asks a store clerk for three answers: the quantity, the unit price and a yes/no confirmation. It converts each answer to the right type and prints an order summary.
Step 1 — Ask the three questions
Section titled “Step 1 — Ask the three questions”quantity_reply = input("Quantity: ")price_reply = input("Unit price (USD): ")confirm_reply = input("Confirm order? (yes/no) ")Each call prints its message, waits for Enter and returns a str. The page cannot type for you, so the next steps use the strings that the clerk would type: " 3 ", "79.99" and "yes".
Step 2 — Convert each reply to the right type
Section titled “Step 2 — Convert each reply to the right type”quantity_reply = " 3 " # the clerk typed spaces around the 3price_reply = "79.99"confirm_reply = "yes"quantity = int(quantity_reply)unit_price = float(price_reply)confirmed = confirm_reply == "yes"print(repr(quantity_reply), "->", quantity, type(quantity))print(repr(price_reply), "->", unit_price, type(unit_price))print(repr(confirm_reply), "->", confirmed, type(confirmed))' 3 ' -> 3 <class 'int'>'79.99' -> 79.99 <class 'float'>'yes' -> True <class 'bool'>A count becomes an int, a price a float and the answer a bool. int() ignores the spaces around the digits. The built-in function repr() shows a value with quotes, as the REPL does, so you can see the spaces.
Step 3 — Print the order summary
Section titled “Step 3 — Print the order summary”order_total = quantity * unit_priceprint(f"{quantity} x {unit_price} USD = {order_total:.2f} USD")print("Confirmed:", confirmed)3 x 79.99 USD = 239.97 USDConfirmed: TrueThe f-string rounds only the display to 2 decimals. Module 03 uses confirmed in an if statement to save the order or cancel it.
Step 4 — See what a bad reply does
Section titled “Step 4 — See what a bad reply does”quantity_reply = "three"quantity = int(quantity_reply)ValueError: invalid literal for int() with base 10: 'three'int() reads digits, not words, so the script stops. Module 06 shows how to ask again instead.
Common mistakes:
- Using a reply without converting it.
" 3 " * 79.99raisesTypeError: can't multiply sequence by non-int of type 'float'. - Using
float()for a count. A quantity of 2.5 pairs of earbuds makes no sense, andint()rejects"2.5". - Converting the yes/no reply with
bool().bool("no")isTrue, because the string is not empty. Compare the text instead:confirm_reply == "yes".
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
A bare expression in a script, such as total |
The script prints nothing | Use print(total) |
Text plus a number: "Units: " + 1375 |
TypeError: can only concatenate str (not "int") to str |
Use an f-string or str(1375) |
Using the result of input() as a number |
TypeError in the first calculation |
Convert with int() or float() |
int("21.7") |
ValueError: invalid literal for int() with base 10 |
Use float(), or int(float("21.7")) |
0.1 + 0.2 == 0.3 |
False |
Use math.isclose(), or compare rounded values |
7 / 2 when you want a whole number |
3.5 |
Use 7 // 2 |
Expecting -7 // 2 to be -3 |
-4 |
// rounds toward minus infinity; use int(-7 / 2) to truncate |
a + b + c / 3 for an average |
A value far above the average | Add parentheses: (a + b + c) / 3 |
-2 ** 2 |
-4 |
** runs before the minus sign; write (-2) ** 2 |
Expecting round(2.5) to be 3 |
2 |
Python rounds halves to the even number |
bool("False") or bool("no") |
True |
Compare the text: answer == "yes" |
x == None |
Works, but linters warn (E711) | Use x is None |
true, false or none |
NameError |
Write True, False, None |
| A typo in a variable name | NameError: name '...' is not defined |
Read the “Did you mean” hint and fix the name |
python report.py typed at >>> |
SyntaxError: invalid syntax |
Leave the REPL with exit(), then run the command |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: form fields and URL parameters arrive as strings. A web shop converts
"3"withint()and rejects"three"before it saves an order. - Automation: a backup script turns 7,385 seconds into “2 h 3 min 5 s” with
//and%, and prints a log line with an f-string. - APIs and pagination: an API sends 50 items per page.
(total_items + 49) // 50gives the number of pages, for example 25 pages for 1,201 items. - Tooling: developers keep a REPL open as a calculator and to test a library call before they put it in a script.
Summary
Section titled “Summary”- The interpreter runs your code. The REPL runs one line at a time and echoes values. A script runs a whole
.pyfile and shows only what youprint(). - A variable is a name for a value.
=assigns;==compares. Use clear snake_case names. - The five basic types are
int,float,bool,strandNone.type()tells you which one you have. /always gives a float.//gives the floor of a division and%gives the remainder. Use parentheses to make the order of operations clear.- Floats are approximate. Round for display and compare with
math.isclose(). - Comparisons give
boolvalues.and,orandnotcombine them.0,0.0,""andNoneare falsy. Nonemarks a missing value. Test it withis None.- Data from files, forms and
input()is text. Convert it withint()orfloat(). A failed conversion raises aValueError. print()shows values; f-strings build readable lines. Comments explain why.
Self-check questions
Section titled “Self-check questions”Q1. What is the difference between the REPL and a script?
Answer
The REPL runs one line at a time and echoes the value of each expression. A script is a .py file that runs from top to bottom and shows only what you pass to print(). Use the REPL to explore and a script for code you keep.
Q2. A script contains only the line 2850 - 1420. What does it print?
Answer
Nothing. The script computes 1430 and throws it away. Write print(2850 - 1420).
Q3. What do type(21.0) and type("21.0") return?
Answer
<class 'float'> and <class 'str'>. The quotes make the second value text.
Q4. What are 17 / 5, 17 // 5 and 17 % 5?
Answer
3.4, 3 and 2. Division always gives a float. Floor division gives the number of whole fives (3). Modulo gives the remainder (17 − 15 = 2).
Q5. Why is 0.1 + 0.2 == 0.3 False, and what should you write instead?
Answer
0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004. Write math.isclose(0.1 + 0.2, 0.3) after import math.
Q6. What does int("21.7") do? How do you get the whole number 21 from the text "21.7"?
Answer
It raises ValueError: invalid literal for int() with base 10: '21.7'. Convert in two steps: int(float("21.7")) gives 21. Use round(float("21.7")) if you want the nearest whole number (22).
Q7. The user types 42 at an input() prompt. What is the type of the value that input() returns?
Answer
str. input() always returns text. Convert it with int() before you calculate.
Q8. What is bool("0")? Why?
Answer
True. Any non-empty string is truthy. Python does not read the characters inside the string. Only the empty string "" is falsy.
Q9. A sensor sends no value. Why store None instead of 0, and how do you test for it?
Answer
0 is a real temperature, so it would hide the gap and distort an average. None says “unknown”. Test it with reading is None.
Q10. What is wrong with average = a + b + c / 3?
Answer
/ runs before +, so only c is divided by 3. Write average = (a + b + c) / 3.
Q11. Which of these names are valid: 2nd_reading, second-reading, second_reading, class?
Answer
Only second_reading. A name cannot start with a digit, cannot contain - and cannot be a keyword such as class.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 25 exercises with hints and full solutions, from warm-up to challenge.
- Mini-project: write a sensor report script from raw readings.
- Cheat sheet: every type, operator and conversion of this module on one page.
- Next module: 02. Strings and text teaches indexing, slicing, string methods and f-string format specs.