random module can simulate a die.math module.Functions are one of the most important ideas in programming. A function is a named block of code that performs a specific task. Instead of writing the same code again and again, we put it inside a function and call it whenever we need it.
This chapter also connects functions with random-number generation, the Python Standard Library, methods, scope, imports, argument passing, recursion, functional-style programming and measures of dispersion. The source chapter specifically uses random numbers to simulate a six-sided die and builds toward the dice game craps.
You have already used built-in functions such as print(), input(), len(), sum(), min() and max(). Now we create our own.
def function_name(parameter):
# function body
return resultdef tells Python that we are defining a function.function_name is the name we choose.return sends a result back to the caller.def square(number):
"""Calculate the square of number."""
return number ** 2
print(square(7))
print(square(2.5))A function can receive more than one input.
def rectangle_area(length, width):
return length * width
area = rectangle_area(10, 5)
print(area)The first argument goes to length and the second goes to width.
Python's Standard Library contains the random module. It provides functions for generating pseudo-random values. In this chapter, random numbers are used to simulate rolling a six-sided die.
import random
for roll in range(5):
print(random.randrange(1, 7))randrange(1, 7) can produce 1 through 6; the ending value 7 is excluded.
Sometimes we want random-looking values but also want the same sequence every time while testing. A random-number generator can be seeded for reproducibility.
import random random.seed(10) print(random.randrange(1, 7))
The chapter combines custom functions and random-number generation to simulate the dice game craps. It also introduces tuples and uses a tuple to return more than one value from a function.
A function can return multiple values together. Python can pack those values into a tuple.
def roll_dice():
import random
die1 = random.randrange(1, 7)
die2 = random.randrange(1, 7)
return die1, die2
first, second = roll_dice()
print(first, second)The important programming lesson is not memorizing a casino game. The lesson is how several functions, random values, conditions and returned values can work together to model a real process.
Python comes with a large collection of reusable modules called the Python Standard Library. Using these capabilities saves you from reinventing the wheel. The chapter imports and uses modules such as random, math and statistics.
import math print(math.sqrt(81))
The math module provides mathematical functions and constants.
| Function / Constant | Meaning | Example |
|---|---|---|
math.sqrt(x) | Square root | math.sqrt(25) → 5.0 |
math.pow(x, y) | x raised to y | math.pow(2, 3) → 8.0 |
math.pi | π | Useful for circles |
math.e | Euler's number | Mathematical constant |
import math radius = 5 area = math.pi * radius ** 2 print(area)
IPython provides tab completion, which helps you discover available names and members while coding. Instead of remembering everything, you can type part of a name and use tab completion to explore what is available.
A parameter can have a default value. If the caller does not provide that argument, Python uses the default.
def describe_pet(name, animal="dog"):
return f"{name} is a {animal}"
print(describe_pet("Buddy"))
print(describe_pet("Milo", "cat"))Here "dog" is the default value for animal.
With positional arguments, Python matches values according to position. With keyword arguments, you explicitly name the parameter.
def rectangle_area(length, width):
return length * width
print(rectangle_area(width=4, length=10))Keyword arguments can make calls clearer, especially when a function has many parameters. The chapter notes that they also let arguments be supplied without depending entirely on their positions.
=: width=4.Sometimes a function needs to accept any number of arguments. Python supports this with *args.
def average(*args):
return sum(args) / len(args)
print(average(5, 10))
print(average(5, 10, 15))
print(average(5, 10, 15, 20))The * tells Python to pack the extra positional arguments into a tuple named args. The name args is conventional, but another identifier can be used. If *args is combined with other parameters, it must be the rightmost parameter.
grades = [88, 75, 96, 55, 83] print(average(*grades))
The *grades expression unpacks the list so its individual elements are passed as separate arguments.
average() with no arguments makes len(args) zero, so the division causes ZeroDivisionError.A method is a function that belongs to an object. You have already seen this idea with string methods.
name = "python" print(name.upper()) print(name.title())
len(name).name.upper().Scope tells us where an identifier can be used. A variable created inside a function normally has local scope.
x = 10
def show_value():
x = 20
print("Inside:", x)
show_value()
print("Outside:", x)The two x names refer to different bindings in different scopes.
There are several ways to import capabilities from a module.
import math print(math.sqrt(36))
from math import sqrt print(sqrt(36))
import statistics as stats grades = [85, 93, 45, 87, 93] print(stats.mean(grades))
The chapter recommends the module-name approach or an alias because it helps reduce accidental name conflicts.
from math import *, names from the module can overwrite names already used in your program. The chapter demonstrates this with the name e.Python arguments are passed using references to objects. The source describes this as pass-by-reference and also notes the term pass-by-object-reference. When a function call supplies an argument, Python copies the reference to the object, not the object itself.
def add_item(items):
items.append("Python")
books = ["Java"]
add_item(books)
print(books)The function receives a reference to the same list object, so mutating the list is visible to the caller.
A recursive function is a function that calls itself, either directly or indirectly through another function.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))The function needs a base case so that the recursive calls eventually stop.
Python supports functional-style programming. This approach often treats functions as values that can be passed to other functions and emphasizes processing data through operations.
A lambda is a small anonymous function.
square = lambda x: x ** 2 print(square(5))
filter() selects elements for which a condition is true.
numbers = [1, 2, 3, 4, 5] odds = list(filter(lambda x: x % 2 != 0, numbers)) print(odds)
map() applies a function to each selected element.
numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x ** 2, numbers)) print(squares)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = list(map(
lambda x: x ** 2,
filter(lambda x: x % 2 != 0, numbers)
))
print(result)The chapter later connects these ideas to functional-style sequence processing and MapReduce.
filter → "Which items should stay?"map → "What should I do to each item?"Earlier, mean, median and mode described the center of data. Measures of dispersion describe how spread out the values are. The chapter introduces variance and standard deviation.
values = [1, 3, 4, 2, 6, 5, 3, 4, 5, 2]
The mean is 3.5. To calculate population variance manually, subtract the mean from each value, square the differences and calculate their mean. For this data, the population variance is 2.25.
import statistics values = [1, 3, 4, 2, 6, 5, 3, 4, 5, 2] print(statistics.pvariance(values)) print(statistics.pstdev(values))
The chapter also shows that math.sqrt(statistics.pvariance(values)) gives 1.5.
| Measure | Simple meaning |
|---|---|
| Variance | Measures how far values spread from the mean, using squared differences. |
| Standard deviation | Square root of variance; it is expressed in the same units as the original data. |
| Small value | Values tend to be closer to the mean. |
| Large value | Values tend to be more spread out. |
The chapter distinguishes population functions pvariance() and pstdev() from sample functions variance() and stdev().
This chapter builds the foundation for writing reusable Python programs with functions. It combines custom functions with random-number generation, introduces tuples for returning multiple values, and demonstrates how the Standard Library helps programmers reuse existing capabilities.
return when a value is needed by the caller.*args function with no values and then dividing by zero.return statement do?random.seed() useful?*args do?import ... as ... work?filter() and map()?average(*args) function that safely handles zero arguments.random to simulate 20 die rolls and count the results.filter() to select even numbers and map() to square them.statistics.Teaching note: This HTML is a beginner-friendly transformative explanation based on the chapter's concepts and structure. It is designed for learning and revision rather than reproducing the book's original text.