7. Functions in Python
About this chapter
Big idea: A function is a named job. You write it once. You call it when you need that job.
This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.
- Say why functions make programs shorter and easier to test.
- Define a function with def. Call it with parentheses.
- Tell a parameter from an argument. Use defaults, keywords, and *args.
- Return a value. Treat a missing return as None.
- Trace a call and a return with a variable table.
- Tell local scope from global scope.
- Use built-in tools such as len, abs, max, min, and sum.
- Import math, random, and statistics. Call their functions.
- Choose import math, from math import name, or an alias.
In 1951 Maurice Wilkes and David Wheeler built the subroutine on the EDSAC computer. Before that, people copied the same punched tape for a repeated job. Wheeler used a jump out of the main program. The jump ran a stored block. Then it came back to the same place. Later languages called those blocks functions. In 1991 Guido van Rossum made functions a core tool in Python. You can pass a function into another function. That keeps programs in small, named parts.
7.1 Why we use functions
A function is a named block of code that does one job.
A short program is easy to read.
A long program is not.
The same lines may appear in many places.
Then one fix needs many edits.
A function is a named group of statements.
You write the steps once.
You give the group a name.
You run that name whenever you need the job.
To run it, you call the function.
A call uses the name and a pair of parentheses.
Python jumps into the function.
It runs the body from top to bottom.
Then it comes back to the caller.
The caller continues with the next line.
A function is a named job you can reuse.
How to read the figure. Look left. Those numbers are arguments. Look at the box. That is the function. Look right. That is the value sent back.
- Function: a named group of instructions that does one task.
- Function call: an instruction that runs a named function.
- Modularity: breaking a large program into small parts.
- Code reuse: using the same code again without rewriting it.
- Modularity: You split a big job into small parts.
- Reuse: You write the function once. You call it many times.
- Less copying: The file stays short.
- Easier tests: You test one small function at a time.
- Team work: People can write different functions, then join them.
| Style | What you write | Benefit |
|---|---|---|
| One long script | All lines in one file | Fine for a tiny test |
| Functions | Named blocks for each job | Easier to test and reuse |
A job may take 4 lines. Six copies need 24 lines.
A 5-line function plus 6 calls is 11 lines.
Copy and paste looks quick.
It is not safe.
A bug in one copy stays in the others.
A function has one body.
Fix that body once.
Every call uses the fixed steps.
- Built-in: Ready tools such as print() and len(). No import.
- Module functions: Tools in files such as math.sqrt(). Import first.
- User-defined: Functions you write with def.
Here the same perimeter formula is typed three times:
print(2 * (25 + 14))
print(2 * (10 + 8))
print(2 * (12 + 9))A function holds the formula once:
def perimeter(length, width):
return 2 * (length + width)
print(perimeter(25, 14))
print(perimeter(10, 8))
print(perimeter(12, 9))The three calls send different lengths and widths.
The formula itself is written only in the body.
That is the point of a function.
Name the job. Hide the steps. Call the name.
A sports ground is 25 m long and 14 m wide. Put the perimeter in a function, then call it.
Goal. Find the perimeter. Show why a function helps.
Rule. Perimeter of a rectangle is 2 × (length + width).
Substitute. 2 × (25 + 14) = 2 × 39.
Calculate. 2 × 39 = 78.
Check. 25 + 25 + 14 + 14 is also 78.
Reuse. Call perimeter(25, 14). Later call it with other sizes.
Result: Result: 78 metres. One function, many calls.
Cover the answers. Try each item on paper first.
7.2 Defining and calling user-defined functions
You create a function with def. You give it a name.
Built-in tools do not cover every task.
Then you write a user-defined function.
You choose the name.
You write the steps.
The first line is the function header.
It starts with def.
Then the name, then (), then a colon.
The next indented lines are the function body.
Indent by four spaces. Keep the indent the same.
def stores the steps. A call with () runs them.
- def: the keyword that starts a new function.
- Function header: the first line of a definition, ending with a colon.
- Function body: the indented statements that do the work.
- Indentation: spaces at the start of a line that group statements.
| Part | Looks like | Job |
|---|---|---|
| def keyword | def | Starts a definition |
| Function name | greet | The name you will call |
| Parentheses | () | Hold parameters |
| Colon | : | Ends the header |
| Indented body | print("Hello!") | Runs when the function is called |
How to read the table. Row 1 is the keyword. Row 5 is the work. Miss the colon and Python stops.
- Start with a letter or an underscore.
- Then use letters, digits, or underscores.
- Do not start with a digit. Do not use spaces.
- Do not use a keyword such as if or for.
- Prefer lowercase with underscores, such as show_banner.
This program defines greet. Then it calls greet twice.
def greet():
print("Welcome to Python functions!")
greet()
greet()Welcome to Python functions!
Welcome to Python functions!Python sees def greet():. It stores the name.
It does not print yet.
The body is only a plan at that moment.
Each greet() call runs the body once.
First call prints the welcome line.
Second call prints the same line again.
So the message prints twice.
You did not copy the print statement.
You reused the name.
This function draws a line of stars:
def show_star_line():
print("*" * 24)
show_star_line()
print("Shelfmark Computer Science")
show_star_line()************************
Shelfmark Computer Science
************************The first call prints the star line.
Then the title prints.
The second call prints the star line again.
The frame is two calls plus one print.
Change the star count in one place only.
Write show_divider() that prints twenty equal signs. Use it to frame the word Start.
Goal. Package a repeated print into a function.
Header. Write def show_divider(): with a colon.
Body. Indent print("=" * 20).
Calls. Call it, print Start, call it again.
Check. You should see a line, then Start, then a line.
Result: Result: the repeated line lives in one reusable command.
Pause here. Answer before you scroll.
7.3 Parameters and arguments
Parameters let a function work with different data.
A function with no inputs always does the same thing.
Most functions need data.
A parameter is a name in the header.
It is an empty slot.
An argument is the real value you pass in the call.
Think of a letter slot and a letter.
The slot is the parameter.
The letter is the argument.
Parameters receive. Arguments are sent.
- Parameter: a name in the header that receives input.
- Argument: the real value passed in a call.
- Positional argument: an argument matched by order from the left.
- Keyword argument: an argument sent as name=value.
- Default parameter: a parameter with a backup value.
- Variable arguments: extra values collected by *name.
| Kind | Where it sits | Example |
|---|---|---|
| Parameter | In the header | def box_volume(length, width, height): |
| Positional argument | In the call, by order | box_volume(4, 5, 10) |
| Keyword argument | In the call, as name=value | box_volume(height=10, width=5, length=4) |
| Default parameter | In the header with = | def make_label(item, count=1): |
| *args | In the header with * | def add_all(*nums): |
How to read the table. Row 1 is a slot. Row 2 fills slots by order. Row 3 names each slot. Row 5 gathers leftover values.
Python matches by position, left to right.
The first argument fills the first parameter.
The counts must match, unless a default fills a gap.
def box_volume(length, width, height):
volume = length * width * height
print("Volume:", volume)
box_volume(4, 5, 10)
box_volume(2, 3, 6)Volume: 200
Volume: 36First call: length 4, width 5, height 10. Volume 200.
Python filled the slots in that order.
Second call uses new numbers. Volume 36.
The body did not change.
Only the arguments changed.
That is why parameters exist.
Any Python value can be an argument.
def print_summary(title, scores):
print("Subject:", title)
print("Total:", sum(scores))
print("Count:", len(scores))
print_summary("Science", [85, 90, 75])Subject: Science
Total: 250
Count: 3The first argument is the subject name as a string.
The second argument is a list of scores.
sum adds the list. len counts the list.
The function does not return those numbers. It prints them.
A default is a backup value in the header.
If the call skips that slot, Python uses the default.
def make_label(item, count=1):
print(count, "x", item)
make_label("Book")
make_label("Pencil", 5)1 x Book
5 x PencilFirst call skips count, so count is 1.
Second call passes 5, so count is 5.
A parameter with no default cannot follow one with a default.
Write def calc(y, x=2):. Do not write def calc(x=2, y):.
A keyword argument uses the parameter name in the call.
Order then does not matter for those names.
def make_tag(item, count=1, unit="pcs"):
print(count, unit, "of", item)
make_tag("Clip")
make_tag("Clip", unit="box")
make_tag(item="Pin", count=3, unit="pack")1 pcs of Clip
1 box of Clip
3 pack of PinThe first call uses both defaults.
The second call names unit only.
The third call names every slot.
After a keyword argument, do not pass a bare positional value.
Python would not know which slot it fills.
A star in the header collects extra positional values.
They arrive as a tuple.
def add_all(*nums):
print(sum(nums))
add_all(1, 2, 3)
add_all(10, 20)6
30The star packs leftover values into a tuple.
First call sums to 6.
Second call sums to 30.
You do not need a new header for each count of numbers.
A list or dict as a default is shared across calls.
def add_mark(mark, bag=[]):
bag.append(mark)
return bag
print(add_mark(1))
print(add_mark(2))[1]
[1, 2]The second call still sees the first mark.
Python builds that default list once.
It does not build a new list on every call.
So the bag grows. That surprises people.
Use None, then make a new list inside:
def add_mark(mark, bag=None):
if bag is None:
bag = []
bag.append(mark)
return bag
print(add_mark(1))
print(add_mark(2))[1]
[2]Now each call starts with a new empty list.
The prints are [1] and then [2].
The two calls no longer share a bag.
A parcel of 8 kg costs 5 per kg plus a fee of 15. What is the cost? How do defaults help?
Goal. Find the cost. Show a default-parameter design.
Rule. cost = weight × rate + fee.
Multiply. 8 × 5 = 40.
Add. 40 + 15 = 55.
Header. def delivery(weight, rate=5, base=15):
Call. delivery(8) uses both defaults.
Result: Result: the cost is 55. Defaults keep common calls short.
Write a short answer. Then check the notes.
7.4 Returning values from a function
A function can send an answer back to the caller.
print shows a value on the screen.
The rest of the program cannot use that screen text.
return sends a value back to the caller.
Python then leaves the function at once.
Lines below that return do not run.
print shows. return gives a value back.
- return: the keyword that sends a value back and exits.
- Fruitful function: a function that returns a useful value.
- Void function: a function that does an action but returns None.
- None: the Python value that means "no value here".
- Composition: using one function’s return as another function’s argument.
A fruitful function returns a value.
The caller can store it, print it, or compute with it.
def square(number):
return number * number
ans1 = square(6)
ans2 = square(9)
print("Square of 6:", ans1)
print("Square of 9:", ans2)
print("Sum of squares:", ans1 + ans2)Square of 6: 36
Square of 9: 81
Sum of squares: 117square(6) is 36. square(9) is 81.
Those two values sit in ans1 and ans2.
Line 8 can add them because they were returned.
If square only printed, the sum line would fail.
def check_sign(n):
if n > 0:
return "Positive"
return "Zero or negative"
print("This line never runs!")
print(check_sign(12))
print(check_sign(-4))Positive
Zero or negativeThe last print in check_sign never runs.
12 is greater than 0, so the first return fires.
-4 fails that test, so the second return fires.
A later print cannot run after a return in the same path.
No return, or a bare return, makes a void function.
Python then gives back None.
def show_team(team_name):
print("Team:", team_name)
result = show_team("Blue")
print("What show_team returned:", result)Team: Blue
What show_team returned: NoneThe team name printed. The stored result is still None.
None is a real object. It is not the word "nothing".
Do not add None to a number. That raises TypeError.
If you need a number later, return it. Do not only print it.
| Feature | print() | return |
|---|---|---|
| Job | Shows text on the screen | Sends data back to the program |
| Who can use it | Only a person reading the screen | Any later line in the program |
| If you skip it | Nothing extra happens | The function yields None |
Comma-separated returns make a tuple.
The caller can unpack the tuple.
def rectangle_stats(width, height):
area = width * height
perimeter = 2 * (width + height)
return area, perimeter
a, p = rectangle_stats(5, 8)
print("Area:", a)
print("Perimeter:", p)Area: 40
Perimeter: 26Area is 40. Perimeter is 26.
The return line packed two numbers.
The caller unpacked them into a and p.
Those names now live in the main program.
Composition means nest one call inside another.
The inner call runs first.
Its return becomes the outer argument.
def add_five(x):
return x + 5
def triple(y):
return y * 3
print(triple(add_five(10)))45add_five(10) is 15.
That 15 becomes the argument of triple.
triple then multiplies by 3. The print is 45.
You can nest more than two calls the same way.
Always finish the inside call first.
A film lasts 2 hours and 35 minutes. How many minutes is that? What should a fruitful function return?
Goal. Convert the length to minutes.
Rule. 1 hour = 60 minutes.
Hours. 2 × 60 = 120.
Add. 120 + 35 = 155.
Return. return that integer, do not only print it.
Check. 2 hours 35 minutes is 155 minutes.
Result: Result: 155 minutes. return sends that integer back.
Test yourself. Then read the explained answers.
7.5 Flow of execution
Flow of execution is the order Python runs statements.
Execution starts at the first line of the file.
Then it walks down, one statement at a time.
A def line stores a name.
Python skips the body until a call.
A call pauses the caller.
Python jumps to the function.
Arguments fill parameters.
The body runs.
On return, Python jumps back to the call site.
The body runs only when you call it.
- Flow of execution: the order statements run.
- Call site: the exact place a function is called.
- Trace: follow each step in order.
How to read the figure. Start at the top. A def is only a record. A call is the jump. return is the path back.
How to read this figure. The left column is the main program. The right column is the functions. Arrows show each jump.
def step_two():
print("Step 2: Inside step_two()")
def step_one():
print("Step 1: Inside step_one()")
step_two()
print("Step 3: Back in step_one()")
print("Start of program")
step_one()
print("End of program")Start of program
Step 1: Inside step_one()
Step 2: Inside step_two()
Step 3: Back in step_one()
End of program- def lines store step_two and step_one. Bodies wait.
- print Start runs.
- step_one() jumps in and prints Step 1.
- step_two() jumps in and prints Step 2.
- Control returns and prints Step 3.
- The main program prints End.
The def lines at the top did not print anything.
Printing started at Start of program.
Nested calls stack. The last call to enter is the first to finish.
step_two finishes before Step 3 prints.
This small program is easy to trace by hand:
def add_five(x):
y = x + 5
return y
n = 10
ans = add_five(n)
print(ans)15| Step | Statement | n | x | y | ans |
|---|---|---|---|---|---|
| 1 | n = 10 | 10 | — | — | — |
| 2 | ans = add_five(n) | 10 | 10 | — | waiting |
| 3 | y = x + 5 | 10 | 10 | 15 | waiting |
| 4 | return y | 10 | 10 | 15 | 15 |
| 5 | print(ans) | 10 | gone | gone | 15 |
How to read the table. Each row is one moment.
x and y exist only inside add_five.
After return those local names are gone.
ans holds 15 in the caller.
A trace table stops you guessing. Fill every cell.
Trace triple(add_five(10)). add_five returns x + 5. triple returns y * 3.
Goal. Find the printed number. Show every step.
Rule. The inner call runs first. That is composition.
Inner. add_five(10) → 10 + 5 = 15.
Pass. 15 becomes y in triple.
Outer. triple(15) → 15 × 3 = 45.
Check. (10 + 5) × 3 = 45.
Result: Result: the program prints 45. Inner call first.
Predict first. Then compare with the notes.
7.6 Scope of variables
Scope is the region where a name can be used.
A variable does not exist everywhere.
Scope is the region where a name is known.
A name made inside a function is local.
A name made outside all functions is global.
Local names live only while the function runs.
- Scope: the part of a program where a name is known.
- Local variable: a name created inside a function.
- Global variable: a name created outside all functions.
- Shadowing: a local name hiding a global name of the same spelling.
How to read the figure. The outer box is the file. The inner box is bonus(). Inner names cannot be read from the outer box.
Parameters are local too.
They are made on the call. They vanish on return.
def set_points():
points = 50
print("Inside set_points:", points)
set_points()Inside set_points: 50print(points) outside set_points raises NameError.
A global name lives until the program ends.
A function may read it without the global keyword.
Reading is allowed. Assigning is not, unless you write global.
level = 3
def show_level():
print("Level:", level)
show_level()Level: 3show_level did not create a local level.
So Python looked outside and found 3.
Shadowing means a local name hides a global one.
The global name is not changed.
points = 100
def bonus():
points = 25
print("Inside bonus:", points)
bonus()
print("Outside bonus:", points)Inside bonus: 25
Outside bonus: 100Inside bonus, points is 25.
That 25 is a new name. It is not the global 100.
Outside, points is still 100.
The local 25 vanished when bonus finished.
This is the example to remember for exams.
To change a global name inside a function, write global first.
counter = 0
def increment():
global counter
counter = counter + 1
increment()
increment()
increment()
print("Final counter:", counter)Final counter: 3Three calls add 1 + 1 + 1. The counter is 3.
Each call changed the same name.
That can be hard to follow in a large file.
Prefer arguments and return values.
Use global names rarely.
| Property | Local | Global |
|---|---|---|
| Where defined | Inside a function | Outside all functions |
| Who can use it | Only that function | The whole file |
| Lifetime | From call to return | Until the program ends |
level = 1 is global. bonus() sets level = 5 locally. What prints inside and outside?
Goal. Predict both printed values.
Rule. A local name shadows a global name of the same spelling.
Inside. The local level is 5, so it prints 5.
Return. Local memory is cleared.
Outside. The global level is still 1, so it prints 1.
Check. The two names never shared storage.
Result: Result: inside 5, outside 1.
Check these without looking down yet.
7.7 Built-in functions in Python
Built-in functions are always ready. You do not import them.
Built-in functions live in Python itself.
You already used print(), input(), and type().
No import line is needed.
Built-ins are always in memory.
- Built-in function: a ready function that needs no import.
- Absolute value: distance from zero, with the sign dropped.
- Unicode code point: the integer for a character, from ord().
- abs(x): distance from zero. abs(-12) is 12.
- max(...): the largest item.
- min(...): the smallest item.
- sum(seq): the total of a list or tuple.
- round(x, n): x rounded to n decimal places.
- pow(x, y): x to the power y, like x ** y.
>>> abs(-15)
15
>>> max([4, 9, 2])
9
>>> min([4, 9, 2])
2
>>> sum([10, 20, 30])
60
>>> round(3.14159, 2)
3.14
>>> pow(2, 5)
32abs drops the minus sign. 15 stays 15.
max of 4, 9, 2 is 9. min is 2.
sum of 10, 20, 30 is 60.
round to 2 places keeps 3.14.
pow(2, 5) is 32.
- len(s): how many items in a string, list, or tuple.
- type(x): the type of x.
- range(start, stop, step): a sequence of integers.
- ord(c): Unicode number of one character. ord("A") is 65.
- chr(n): character for that number. chr(65) is A.
- bin(n): binary string starting with 0b.
- oct(n): octal string starting with 0o.
- hex(n): hexadecimal string starting with 0x.
>>> ord("A")
65
>>> chr(65)
A
>>> bin(12)
0b1100
>>> hex(255)
0xfford and chr are a pair. One undoes the other.
bin and hex only change how the integer is shown.
The number itself is still an int inside Python.
marks = [14, 18, 12, 20, 16]
print("Highest:", max(marks))
print("Lowest:", min(marks))
print("Total:", sum(marks))
print("Count:", len(marks))
print("Average:", round(sum(marks) / len(marks), 2))
print("Spread:", max(marks) - min(marks))Highest: 20
Lowest: 12
Total: 80
Count: 5
Average: 16.0
Spread: 8The five marks total 80.
Count is 5, so the average is 80 / 5 = 16.
Spread is 20 − 12 = 8.
No user-defined function was needed here.
The built-ins already did the jobs.
| Function | Job | Call | Result |
|---|---|---|---|
| abs(x) | Distance from zero | abs(-8) | 8 |
| max(seq) | Largest item | max([3, 7, 1]) | 7 |
| min(seq) | Smallest item | min([3, 7, 1]) | 1 |
| sum(seq) | Total | sum([5, 10, 15]) | 30 |
| round(x, n) | Round to n places | round(4.678, 1) | 4.7 |
| pow(x, y) | Power | pow(2, 3) | 8 |
| len(seq) | Count | len("Book") | 4 |
| ord(c) | Code of a character | ord("B") | 66 |
| chr(n) | Character of a code | chr(66) | B |
How to read the table. The last column is the value Python gives back. sum needs a list or tuple, not three loose numbers.
Readings are 8, 14, 6, 12, and 10. Find lowest, highest, and spread.
Goal. Use min, max, and a subtract.
Lowest. min of the five values is 6.
Highest. max of the five values is 14.
Spread. 14 − 6 = 8.
Check. The list sums to 50, so the data is the same set.
Result: Result: spread is 8.
Say the answer out loud. Then read the notes.
7.8 Standard library modules: math, random, and statistics
A module is a file of related tools. You import it when you need it.
Python does not load every tool at start.
Extra tools sit in modules.
The Python Standard Library is the set that ships with Python.
This lesson uses math, random, and statistics.
import brings a module into your program.
Import first. Then call module.name().
- Module: a Python file of functions and values you can import.
- Standard library: the modules that come with Python.
- Pseudo-random: numbers from a formula that look random.
- Seed: the starting number of that formula.
How to read the figure. The first box is the import line. The last box is a call with a dot. Skip the import and Python raises NameError.
- math.pi: the constant π.
- math.sqrt(x): square root, as a float.
- math.ceil(x): round up. math.ceil(4.2) is 5.
- math.floor(x): round down. math.floor(4.9) is 4.
- math.fabs(x): absolute value as a float.
- math.pow(x, y): x to the power y, as a float.
import math
print("Square root of 81:", math.sqrt(81))
print("Ceiling of 4.2:", math.ceil(4.2))
print("Floor of 4.9:", math.floor(4.9))
print("Absolute of -7.5:", math.fabs(-7.5))
print("Pi rounded:", round(math.pi, 4))Square root of 81: 9.0
Ceiling of 4.2: 5
Floor of 4.9: 4
Absolute of -7.5: 7.5
Pi rounded: 3.1416round(math.pi, 4) is 3.1416.
sqrt, ceil, and floor all need the math. prefix in this style.
ceil of 4.2 is 5. The value moved up.
floor of 4.9 is 4. The value moved down.
For a negative number, floor still moves toward minus infinity.
You will practise that in the end exercises.
A computer uses a formula, not true chance.
The same seed gives the same sequence.
That helps tests.
- random.seed(n): fix the start of the sequence.
- random.random(): a float from 0.0 up to, but not including, 1.0.
- random.randint(a, b): an integer from a to b, both ends included.
- random.randrange(start, stop, step): an integer from a range.
- random.choice(seq): one item from a list or string.
import random
random.seed(7)
print("Random float:", round(random.random(), 4))
print("Roll 1:", random.randint(1, 6))
print("Roll 2:", random.randint(1, 6))
print("Picked letter:", random.choice(["A", "B", "C", "D"]))Random float: 0.3238
Roll 1: 2
Roll 2: 4
Picked letter: AThe seed is 7, so every run of this file matches.
Change the seed and the rolls change.
Leave the seed out and tests become noisy.
randint includes both ends. range does not.
- statistics.mean(data): the average, sum divided by count.
- statistics.median(data): the middle value after sorting.
- statistics.mode(data): the value that appears most often.
import statistics
data = [10, 12, 14, 12, 16, 12, 22]
print("Mean:", statistics.mean(data))
print("Median:", statistics.median(data))
print("Mode:", statistics.mode(data))Mean: 14
Median: 12
Mode: 12The seven numbers total 98.
Mean is 98 / 7 = 14.
Sorted, the middle value is 12. That is the median.
12 appears three times. That is the mode.
| Module | Call | Job | Sample result |
|---|---|---|---|
| math | math.sqrt(49) | Square root as a float | 7.0 |
| math | math.ceil(3.1) | Round up | 4 |
| math | math.floor(3.9) | Round down | 3 |
| random | random.randint(1, 10) | Integer from 1 to 10 | One integer in that range |
| random | random.choice(seq) | One random item | One element |
| statistics | statistics.mean(seq) | Average | A mean |
| statistics | statistics.median(seq) | Middle value | The middle |
| statistics | statistics.mode(seq) | Most common value | The mode |
A square room has area 49. Tiles are 2 m long. How long is one wall, and how many whole tiles cover it?
Goal. Wall length, then whole tiles.
Root. math.sqrt(49) = 7.
Divide. 7 / 2 = 3.5.
Ceil. math.ceil(3.5) = 4.
Check. 4 tiles × 2 m = 8 m, which covers 7 m.
Result: Result: wall 7 m. Need 4 whole tiles.
Work these on paper. Then match the notes.
7.9 Different ways to import modules
You can import a whole module, a few names, or a short alias.
import brings tools from another file.
Python offers a few spellings.
Each spelling changes how you write the call.
Prefer import math. Then write math.sqrt.
- import: the statement that loads a module.
- from ... import: a style that copies chosen names into this file.
- Alias: a short nickname after as.
- Namespace: a box of names that stops clashes.
This is the safest default.
Call with a dot: module.function().
import math
print("Square root:", math.sqrt(49))
print("Pi:", round(math.pi, 2))Square root: 7.0
Pi: 3.14You always see math. in the call. Clashes are rare.
The name sqrt still belongs to the module.
Your own variable named sqrt would not overwrite math.sqrt.
That is the point of a namespace.
Bring only the names you need.
from math import sqrt, ceil
print("Square root:", sqrt(64))
print("Ceiling:", ceil(7.1))Square root: 8.0
Ceiling: 8Now you write sqrt(), not math.sqrt().
That saves typing when the name is used often.
Do not later create a variable named sqrt.
That would hide the imported function.
The error then looks like a math bug. It is a name clash.
An alias is a short nickname.
import statistics as st
scores = [5, 8, 8, 9, 10]
print("Mean:", st.mean(scores))
print("Mode:", st.mode(scores))Mean: 8
Mode: 8st stands for statistics here.
Pick a short alias. Keep it through the file.
Do not mix statistics.mean and st.mean at random.
One alias, used every time, is easier to read.
The star means “bring every name”.
That is a wildcard import.
It can overwrite your names with no warning.
A later reader cannot see where sqrt came from.
Stick to import math, or name the tools you need.
| Style | Write | Call | Use when |
|---|---|---|---|
| Whole module | import math | math.sqrt(25) | Default. Clear and safe |
| Chosen names | from math import sqrt | sqrt(25) | A few names, used often |
| Alias | import statistics as st | st.mean(data) | The module name is long |
| Wildcard | from math import * | sqrt(25) | Avoid. Names can clash |
How to read the table. Column 3 is what you type after the import. The last row is the style to skip.
A program uses math.pi and math.sqrt four times each. How can you drop the math. prefix?
Goal. Import only the two names you need.
Change. from math import pi, sqrt
Calls. Write pi and sqrt(...) with no prefix.
Check. A later import math is not required for those two names.
Result: Result: from math import pi, sqrt lets you write pi and sqrt directly.
Try one more set. Answers sit below.
Summary
- A function is a named job. Call it to run the job.
- Functions cut copying. They make tests smaller.
- def, a name, (), and a colon start a definition. Indent the body.
- Parameters are slots. Arguments are the values you pass.
- Match by order, or by keyword. Defaults sit on the right. *args collects extras.
- Do not use a list as a default. Use None and build a new list.
- return sends a value back. No return means None. Inner calls run first.
- Local names live in the call. Global names live in the file. Shadowing hides the global name.
- Built-ins such as len, abs, max, min, and sum need no import.
- import loads a module. Prefer import math. Avoid import *.
- Composition means the inner call runs first. Its return feeds the outer call.
- Keyword arguments fill slots by name. *args packs extra values into a tuple.
Exercises
These questions are new. Show your thinking. For programs, write your answer before you run the code.
7.1 What is the difference between defining a function and calling it?
7.2 This header is def compute(a, b = 10, c):. Why is it a SyntaxError?
7.3 Predict the output of this program.
def make_tag(label, code="A1"):
print(code, label)
make_tag("Box")
make_tag("Bag", "B2")7.4 Predict the output of this program.
def add_bonus(score):
total = score + 15
return total
points = add_bonus(35)
print("Points:", points)7.5 Predict what this program prints.
def announce(msg):
print("Notice:", msg)
result = announce("Meeting at noon")
print("Result is:", result)7.6 What does this program print?
points = 10
def update_points():
points = 40
print("Inside:", points)
update_points()
print("Outside:", points)7.7 Predict the math-module output.
import math
print(math.floor(6.7))
print(math.ceil(6.2))
print(math.floor(-4.1))
print(math.ceil(-4.9))7.8 Predict the seeded random output.
import random
random.seed(12)
print(random.randint(10, 20))
print(random.randint(10, 20))7.9 Predict the statistics output for [6, 7, 7, 8, 12].
import statistics
data = [6, 7, 7, 8, 12]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))7.10 What does this program print?
def swap(a, b):
return b, a
first, second = swap(10, 25)
print("first =", first, "second =", second)7.11 What does each call print?
def speed_warning(speed):
if speed <= 40:
return "Safe"
if speed <= 60:
return "Normal"
return "Fast"
print(speed_warning(30))
print(speed_warning(55))
print(speed_warning(75))7.12 Why does this program raise a NameError on the print line?
def double_number(n):
doubled = n * 2
return doubled
double_number(8)
print(doubled)7.13 Predict the built-in output.
vals = [15, 3, 27, 9]
print("Sum:", sum(vals))
print("Max:", max(vals))
print("Min:", min(vals))
print("Count:", len(vals))7.14 Predict the global-variable output.
score = 50
def add_bonus(points):
global score
score = score + points
add_bonus(15)
add_bonus(10)
print("Final score:", score)7.15 Trace this program and predict the output.
def first():
print("Step 1")
def second():
first()
print("Step 2")
print("Start")
second()
print("End")7.16 What does this program print?
def is_even(number):
return number % 2 == 0
print("14 is even:", is_even(14))
print("9 is even:", is_even(9))Answers
- 7.1: def stores the name and the steps. A call with parentheses runs those steps.
- 7.2: A parameter with no default cannot follow one with a default. c needs a default too, or b must lose its default.
- 7.3: prints A1 Box, then B2 Bag.
- 7.4: Points: 50.
- 7.5: prints Notice: Meeting at noon, then Result is: None. announce has no return, so it yields None.
- 7.6: prints Inside: 40, then Outside: 10. Local points hides global points. The global value stays 10.
- 7.7: prints 6, then 7, then -5, then -4. floor goes toward minus infinity. ceil goes toward plus infinity.
- 7.8: prints 17, then 14.
- 7.9: prints 8, then 7, then 7. Mean is 8. Median is 7. Mode is 7.
- 7.10: first = 25 second = 10. Python packs a tuple and unpacks it into first and second.
- 7.11: prints Safe, then Normal, then Fast.
- 7.12: doubled is local to double_number(). After the call, that name is gone. The main program cannot read it.
- 7.13: prints Sum: 54, then Max: 27, then Min: 3, then Count: 4.
- 7.14: Final score: 75.
- 7.15: prints Start, then Step 1, then Step 2, then End. second() calls first() before it prints Step 2.
- 7.16: prints 14 is even: True, then 9 is even: False.