Module 2 · Python for Data · Lesson 6 of 51

Functions, conditions and errors

if/elif/else, writing reusable functions with parameters and return values, handling bad data with try/except, and importing modules.

In this lesson · about 40 minutes

  • Branch with if, elif and else, combining conditions with and, or and not
  • Write a function with parameters, a default value and a return value
  • Handle bad input with try/except, and import modules such as math and statistics

Conditions

if total >= 20:
    size = "large"
elif total >= 8:
    size = "medium"
else:
    size = "small"

Python checks from the top and runs the first block whose condition is true. Combine conditions with and, or and not. Indentation (4 spaces) is how Python knows which lines belong to the block.

Functions

def discounted(price, pct=10):
    """Price after a percentage discount, rounded to cents."""
    return round(price * (1 - pct / 100), 2)

discounted(4.50)        # 4.05, uses the default 10%
discounted(4.50, 25)    # 3.38

def starts a function; the names in brackets are parameters; pct=10 is a default; return hands back the answer. A function without return gives back None, a classic bug. The text in triple quotes is a docstring explaining what it does.

Lambda functions are one-line, nameless functions, often used for sorting: sorted(items, key=lambda pair: pair[1]) sorts pairs by their second value. You will use them with pandas' apply.

Errors and try/except

Real data contains surprises: float("n/a") raises a ValueError. Instead of crashing on row 3,000, catch the error:

try:
    qty = int(raw)
except ValueError:
    qty = None   # record it as missing and carry on

Read error messages from the bottom: the last line says what went wrong (KeyError: 'Tea'), the line above says where.

Modules

Python's power is in its libraries. import math, import statistics, from datetime import date. Data scientists import pandas, NumPy and Matplotlib with standard nicknames: import pandas as pd, import numpy as np, import matplotlib.pyplot as plt.

Functions and safe conversion

Exercise

Loyalty tier function

Write a function tier(visits) that returns "Gold" for 20 or more visits, "Silver" for 10 to 19, and "Bronze" otherwise.

Exercise

Average, skipping bad values

Write safe_mean(values) that converts each value with float(), skips any that raise ValueError, and returns the average of the rest rounded to 2 decimals.

Check your understanding0 of 4 correct

Question 1

1.A function has no return line. What does calling it give?

Question 2

2.Where do you look first in an error message?

Question 3

3.Which import is the standard way to load pandas?

Question 4

4.if x > 10: … elif x > 5: … For x = 12, which runs?

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.