Skip to content

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.

  • 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, str and None) and check a type with type().
  • 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.

You need no programming experience. This is the first module.

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 (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”.

Terminal
python # start the REPL (use python3 if no environment is active)

To leave the REPL, type exit() or press Ctrl+D.

Here is a short session. You type the text after >>> . The other lines are Python’s answers.

>>> 21.5 + 0.4
21.9
>>> 2850 - 1420
1430
>>> "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.

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
# hello.py: your first Python script.
print("Hello from a script!")
print("Python is ready for data work.")
Output
Hello from a script!
Python is ready for data work.

Run it from a terminal that is open in the same folder:

Terminal
python hello.py

print() 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

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.7
sensor_id = "S1"
print(sensor_id, temperature)
Output
S1 21.7

The = 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.1
temperature = temperature + 0.5
print(temperature)
Output
22.6

Python 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.

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 defined

Python 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.

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 and 79.99 is 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_228 is the integer 20228.
  • 1e-3 is scientific notation (a number times a power of 10) for 0.001. It is a float.
  • \n inside a string is an escape sequence: a backslash code for one special character. \n is the line break at the end of each line of a text file.
  • "21.7" in quotes is a str, not a number. Data from files, forms and the web arrives as text. You convert it before you calculate.
  • True, False and None start with a capital letter. true gives a NameError.

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 / 2 is 5.0.
  • Floor division // divides and then rounds down to a whole number. 250 units fill 250 // 12 = 20 full boxes of 12.
  • Modulo % gives the remainder of the division. The last box has 250 % 12 = 10 units.
  • For any whole numbers a and b (with b not 0), (a // b) * b + a % b equals a.
  • “Rounds down” means toward minus infinity. So -7 // 2 is -4, not -3.
  • When you mix an int and a float, the result is a float: 2 * 1.5 is 3.0.
>>> 10 / 2
5.0
>>> 250 // 12
20
>>> 250 % 12
10
>>> -7 // 2
-4
>>> 120 / 0
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
ZeroDivisionError: division by zero

Precedence 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 / 3
50.03333333333333
>>> (21.0 + 21.9 + 21.4) / 3
21.433333333333334
>>> -2 ** 2
-4
>>> (-2) ** 2
4

The 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.

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.2
0.30000000000000004
>>> 3 * 79.99
239.96999999999997
>>> 0.1 + 0.2 == 0.3
False
>>> round(0.1 + 0.2, 2)
0.3
>>> import math
>>> math.isclose(0.1 + 0.2, 0.3)
True

This 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:

  1. Round only for display, with round(x, 2) or an f-string (see Output). Keep the full value for further calculations.
  2. Do not compare floats with ==. Use math.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 line import math loads the math module, a file of extra tools that comes with Python. Module 08 explains imports. Module 09 tours math.
  3. round() rounds a value that is exactly halfway to the nearest even number: round(2.5) is 2 and round(3.5) is 4. 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…), so round(2.675, 2) gives 2.67.

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.0
True
>>> tenure_months = 4
>>> logins_last_30d = 12
>>> tenure_months <= 6 and logins_last_30d <= 3
False
>>> tenure_months <= 6 or logins_last_30d <= 3
True

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")
True

The 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 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 None
True
>>> reading == 0
False
>>> reading + 1
Traceback (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 (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))
Output
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)
Output
TypeError: can only concatenate str (not "int") to str

Python 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".

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.94
print("Store", store, "total:", total)
print("2024", "05", "01", sep="-")
print("Loading readings...", end=" ")
print("done")
Output
Store S01 total: 458.94
2024-05-01
Loading readings... done

An 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 = 1375
unit_price = 79.99
revenue = units * unit_price
print(f"{product}: {units} units, revenue {revenue}")
print(f"{product}: {units:,} units, revenue {revenue:,.2f} USD")
Output
Wireless Earbuds: 1375 units, revenue 109986.25
Wireless Earbuds: 1,375 units, revenue 109,986.25 USD

Module 02 covers f-strings and format specs in depth.

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:

ask_quantity.py
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 3
print(type(quantity_text))
quantity = int(quantity_text)
print(type(quantity), quantity * 79.99)
Output
<class 'str'>
<class 'int'> 239.96999999999997

Data 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.

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.35
raw_reading = 22.9
corrected = raw_reading - daily_drift # still a float
print(round(corrected, 2))
Output
22.55

A 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.

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_3
458.94
>>> (order_1 + order_2 + order_3) / 3
152.98

The 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
# report.py: summarize today's orders for store S01 (Chicago).
# Each value is the revenue of one order, in USD.
order_1 = 79.99
order_2 = 249.00
order_3 = 129.95
order_count = 3
total = order_1 + order_2 + order_3
average = total / order_count
print("Store S01 daily report")
print("Orders:", order_count)
print("Total revenue:", round(total, 2))
print("Average order:", round(average, 2))
Output
Store S01 daily report
Orders: 3
Total revenue: 458.94
Average order: 152.98

The 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”
Terminal
python report.py
Output
Store S01 daily report
Orders: 3
Total revenue: 458.94
Average order: 152.98

This 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 total in the script. They print nothing. Use print(total).
  • Typing python report.py at the >>> prompt. That is a terminal command, not Python code, so the REPL gives a SyntaxError. Leave the REPL first with exit().
  • Running the command from another folder. Python then says can't open file ... No such file or directory. Change to the project folder with cd first.

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.

raw = "21.7"
print(raw, type(raw))
print(raw + raw)
Output
21.7 <class 'str'>
21.721.7

A 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.

celsius = float(raw)
print(celsius, type(celsius))
print(celsius + celsius)
Output
21.7 <class 'float'>
43.4

float() 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.

fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit)
print(round(fahrenheit, 1))
Output
71.06
71.1

The formula is °F = °C × 9 / 5 + 32. Precedence does the right thing here: * and / run before +. Round only when you show the value.

bad_raw = "error"
print(float(bad_raw))
Output
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 a ValueError because int() accepts only whole-number text. Use float().
  • Doing arithmetic before the conversion. "21.7" * 2 gives "21.721.7", and "21.7" + 1 raises a TypeError.
  • 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 = 1000
interval_minutes = 10
minutes = reading_number * interval_minutes
print(minutes)
Output
10000

Reading 1000 comes 10,000 minutes after the first reading. All values are int, so the result is an int.

minutes_per_day = 24 * 60
days = minutes // minutes_per_day
minutes_left = minutes % minutes_per_day
print(days, minutes_left)
Output
6 1360

A 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 // 60
mins = minutes_left % 60
day_of_month = 1 + days
print(f"2024-05-{day_of_month:02d} {hours:02d}:{mins:02d}")
Output
2024-05-07 22:40

The 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.

rebuilt = days * minutes_per_day + hours * 60 + mins
print(rebuilt, rebuilt == minutes)
Output
10000 True

Rebuilding 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 / 1440 is 6.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 // 100 and % 100 instead 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.

quantity = 3
unit_price = 249.00
discount = 0.1
print(type(quantity), type(unit_price), type(discount))
Output
<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 - discount
revenue = quantity * unit_price * (1 - discount)
print(wrong)
print(revenue)
Output
746.9
672.3000000000001

Without 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")
Output
Revenue: 672.3
Revenue: 672.30 USD

round(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.

import math
print(revenue == 672.3)
print(math.isclose(revenue, 672.3))
Output
False
True

== 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 10 instead of 0.1. The result is negative: 3 * 249.00 * (1 - 10) is -6723.0.
  • Leaving out the parentheses around 1 - discount.
  • Comparing money with ==. Use math.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.

customer_id = "C03991"
tenure_months = 6
logins_last_30d = 2
has_autopay = 0
avg_session_minutes = None # the file says 6.4; None simulates a gap
print(customer_id, tenure_months, logins_last_30d, has_autopay, avg_session_minutes)
Output
C03991 6 2 0 None

These 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.

short_tenure = tenure_months <= 6
low_logins = logins_last_30d <= 3
print(short_tenure, low_logins)
Output
True True

Each 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_logins
watch_list = short_tenure or low_logins
print("At risk:", at_risk)
print("Watch list:", watch_list)
print("Autopay:", bool(has_autopay))
Output
At risk: True
Watch list: True
Autopay: False

and needs both rules. or needs one. bool(has_autopay) turns the stored 0 into False, because 0 is falsy.

print("Session data missing:", avg_session_minutes is None)
Output
Session data missing: True

is None reports the missing value without crashing. Arithmetic on the missing value does crash:

print(avg_session_minutes * 2)
Output
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, and 5 is truthy, so the result is never False. Write each comparison in full.
  • Testing avg_session_minutes == None. It works for None, but PEP 8 asks for is 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.

checkout.py
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 3
price_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))
Output
' 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.

order_total = quantity * unit_price
print(f"{quantity} x {unit_price} USD = {order_total:.2f} USD")
print("Confirmed:", confirmed)
Output
3 x 79.99 USD = 239.97 USD
Confirmed: True

The f-string rounds only the display to 2 decimals. Module 03 uses confirmed in an if statement to save the order or cancel it.

quantity_reply = "three"
quantity = int(quantity_reply)
Output
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.99 raises TypeError: 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, and int() rejects "2.5".
  • Converting the yes/no reply with bool(). bool("no") is True, because the string is not empty. Compare the text instead: confirm_reply == "yes".
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
  • Web development: form fields and URL parameters arrive as strings. A web shop converts "3" with int() 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) // 50 gives 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.
  • The interpreter runs your code. The REPL runs one line at a time and echoes values. A script runs a whole .py file and shows only what you print().
  • A variable is a name for a value. = assigns; == compares. Use clear snake_case names.
  • The five basic types are int, float, bool, str and None. 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 bool values. and, or and not combine them. 0, 0.0, "" and None are falsy.
  • None marks a missing value. Test it with is None.
  • Data from files, forms and input() is text. Convert it with int() or float(). A failed conversion raises a ValueError.
  • print() shows values; f-strings build readable lines. Comments explain why.

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.

Your progress

0 / 4 done

  • 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.