←
Class 11 Computer Science
7. Functions in Python · 7 / 11
⌕
Chapter 7 of 11

7. Functions in Python

12 sections · 6,865 words

About this chapter

238 words · 1 min read

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

659 words · 3 min read

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.

4, 5, 10box_volume200argumentsfunctionreturn
A function is a machine. Arguments go in. A return value comes out.

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.
StyleWhat you writeBenefit
One long scriptAll lines in one fileFine for a tiny test
FunctionsNamed blocks for each jobEasier 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.

Why it matters: one change in the function updates every call.

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

Python
print(2 * (25 + 14))
print(2 * (10 + 8))
print(2 * (12 + 9))

A function holds the formula once:

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

Watch out: Defining is not calling. def only stores the steps. The body runs when you call the name.

⚡ Quick Check Flashcards4 questions
Question 1
What is a function?
Try answering before revealing!
Question 2
What does modularity mean?
Try answering before revealing!
Question 3
Name two gains from functions.
Try answering before revealing!
Question 4
Which kind needs no import line?
Try answering before revealing!

7.2 Defining and calling user-defined functions

551 words · 3 min read

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.
PartLooks likeJob
def keyworddefStarts a definition
Function namegreetThe 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.

Python
def greet():
    print("Welcome to Python functions!")

greet()
greet()

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

Python
def show_star_line():
    print("*" * 24)

show_star_line()
print("Shelfmark Computer Science")
show_star_line()

Output
************************
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.

Type the name with (). A bare name shows the function object. It does not run.

Pause here. Answer before you scroll.

Watch out: Miss the colon after def and you get a SyntaxError. Miss the () on a call and the body never runs.

⚡ Quick Check Flashcards4 questions
Question 1
Which keyword starts a user-defined function?
Try answering before revealing!
Question 2
Why indent the body?
Try answering before revealing!
Question 3
What if you write greet with no parentheses?
Try answering before revealing!
Question 4
Does def run the body at once?
Try answering before revealing!

7.3 Parameters and arguments

872 words · 4 min read

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.
KindWhere it sitsExample
ParameterIn the headerdef box_volume(length, width, height):
Positional argumentIn the call, by orderbox_volume(4, 5, 10)
Keyword argumentIn the call, as name=valuebox_volume(height=10, width=5, length=4)
Default parameterIn the header with =def make_label(item, count=1):
*argsIn 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.

Python
def box_volume(length, width, height):
    volume = length * width * height
    print("Volume:", volume)

box_volume(4, 5, 10)
box_volume(2, 3, 6)

Output
Volume: 200
Volume: 36

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

Python
def print_summary(title, scores):
    print("Subject:", title)
    print("Total:", sum(scores))
    print("Count:", len(scores))

print_summary("Science", [85, 90, 75])

Output
Subject: Science
Total: 250
Count: 3

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

Python
def make_label(item, count=1):
    print(count, "x", item)

make_label("Book")
make_label("Pencil", 5)

Output
1 x Book
5 x Pencil

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

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

Output
1 pcs of Clip
1 box of Clip
3 pack of Pin

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

Python
def add_all(*nums):
    print(sum(nums))

add_all(1, 2, 3)
add_all(10, 20)

Output
6
30

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

Python
def add_mark(mark, bag=[]):
    bag.append(mark)
    return bag

print(add_mark(1))
print(add_mark(2))

Output
[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:

Python
def add_mark(mark, bag=None):
    if bag is None:
        bag = []
    bag.append(mark)
    return bag

print(add_mark(1))
print(add_mark(2))

Output
[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.

Watch out: Never put a list as a default value. Use None and build a new list in the body. Also keep defaults on the right of the header.

⚡ Quick Check Flashcards4 questions
Question 1
Parameter versus argument?
Try answering before revealing!
Question 2
How do positional arguments match?
Try answering before revealing!
Question 3
Where do default parameters sit?
Try answering before revealing!
Question 4
What does *nums collect?
Try answering before revealing!

7.4 Returning values from a function

691 words · 3 min read

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.

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

Output
Square of 6: 36
Square of 9: 81
Sum of squares: 117

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

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

Output
Positive
Zero or negative

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

Python
def show_team(team_name):
    print("Team:", team_name)

result = show_team("Blue")
print("What show_team returned:", result)

Output
Team: Blue
What show_team returned: None

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

Featureprint()return
JobShows text on the screenSends data back to the program
Who can use itOnly a person reading the screenAny later line in the program
If you skip itNothing extra happensThe function yields None

Comma-separated returns make a tuple.

The caller can unpack the tuple.

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

Output
Area: 40
Perimeter: 26

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

Python
def add_five(x):
    return x + 5

def triple(y):
    return y * 3

print(triple(add_five(10)))

Output
45

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

Watch out: print is not return. A function that only prints gives None. Later maths then fails.

⚡ Quick Check Flashcards4 questions
Question 1
What does return do?
Try answering before revealing!
Question 2
What is a void function?
Try answering before revealing!
Question 3
What comes back if there is no return?
Try answering before revealing!
Question 4
How does Python pack two returned values?
Try answering before revealing!

7.5 Flow of execution

676 words · 3 min read

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.
Python records each def namePython skips the body until a callA call jumps into the functionParameters receive the argumentsThe body runs line by linereturn sends a value backThe caller continues after the call
Flow of execution into a function and back to the caller

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.

print Startcall step_one()print Step 1call step_two()print Step 2print Step 3print End
A call jumps into a function. A return jumps back to the caller.

How to read this figure. The left column is the main program. The right column is the functions. Arrows show each jump.

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

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

Python
def add_five(x):
    y = x + 5
    return y

n = 10
ans = add_five(n)
print(ans)

Output
15
StepStatementnxyans
1n = 1010———
2ans = add_five(n)1010—waiting
3y = x + 5101015waiting
4return y10101515
5print(ans)10gonegone15

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.

Watch out: Do not read the page from top to bottom as run order. A body runs only when called. It may run many times, or never.

⚡ Quick Check Flashcards4 questions
Question 1
Where does execution begin?
Try answering before revealing!
Question 2
What does Python do at def?
Try answering before revealing!
Question 3
Where does Python go after a function ends?
Try answering before revealing!
Question 4
In double(add(2, 3)), which runs first?
Try answering before revealing!

7.6 Scope of variables

596 words · 3 min read

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.
Global scopescore = 100readable from insideLocal scope of bonus()points = 25erased on returnouter code cannot see it
Global scope is the whole file. Local scope lives only while the function runs.

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.

Python
def set_points():
    points = 50
    print("Inside set_points:", points)

set_points()

Output
Inside set_points: 50

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

Python
level = 3

def show_level():
    print("Level:", level)

show_level()

Output
Level: 3

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

Python
points = 100

def bonus():
    points = 25
    print("Inside bonus:", points)

bonus()
print("Outside bonus:", points)

Output
Inside bonus: 25
Outside bonus: 100

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

Python
counter = 0

def increment():
    global counter
    counter = counter + 1

increment()
increment()
increment()
print("Final counter:", counter)

Output
Final counter: 3

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

PropertyLocalGlobal
Where definedInside a functionOutside all functions
Who can use itOnly that functionThe whole file
LifetimeFrom call to returnUntil 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.

Watch out: A local name is gone after return. Reading it outside raises NameError: name is not defined.

⚡ Quick Check Flashcards4 questions
Question 1
What is scope?
Try answering before revealing!
Question 2
How long does a local variable live?
Try answering before revealing!
Question 3
What is shadowing?
Try answering before revealing!
Question 4
Which keyword lets a function change a global name?
Try answering before revealing!

7.7 Built-in functions in Python

600 words · 3 min read

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

abs 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.
Python
>>> ord("A")
65
>>> chr(65)
A
>>> bin(12)
0b1100
>>> hex(255)
0xff

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

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

Output
Highest: 20
Lowest: 12
Total: 80
Count: 5
Average: 16.0
Spread: 8

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

FunctionJobCallResult
abs(x)Distance from zeroabs(-8)8
max(seq)Largest itemmax([3, 7, 1])7
min(seq)Smallest itemmin([3, 7, 1])1
sum(seq)Totalsum([5, 10, 15])30
round(x, n)Round to n placesround(4.678, 1)4.7
pow(x, y)Powerpow(2, 3)8
len(seq)Countlen("Book")4
ord(c)Code of a characterord("B")66
chr(n)Character of a codechr(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.

Watch out: sum(1, 2, 3) is a TypeError. Wrap the numbers: sum([1, 2, 3]).

⚡ Quick Check Flashcards4 questions
Question 1
What does abs() return?
Try answering before revealing!
Question 2
Which function counts characters in a string?
Try answering before revealing!
Question 3
ord versus chr?
Try answering before revealing!
Question 4
What is pow(3, 2)?
Try answering before revealing!

7.8 Standard library modules: math, random, and statistics

747 words · 3 min read

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.
Write import math at the topPython loads the math moduleNames sit in the math namespaceCall math.sqrt(49) with a dotThe function returns 7.0
Import flow. Load the module. Then call a name with a dot.

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

Output
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.1416

round(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.
Python
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"]))

Output
Random float: 0.3238
Roll 1: 2
Roll 2: 4
Picked letter: A

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

Output
Mean: 14
Median: 12
Mode: 12

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

ModuleCallJobSample result
mathmath.sqrt(49)Square root as a float7.0
mathmath.ceil(3.1)Round up4
mathmath.floor(3.9)Round down3
randomrandom.randint(1, 10)Integer from 1 to 10One integer in that range
randomrandom.choice(seq)One random itemOne element
statisticsstatistics.mean(seq)AverageA mean
statisticsstatistics.median(seq)Middle valueThe middle
statisticsstatistics.mode(seq)Most common valueThe 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.

Watch out: random.randint(1, 6) can be 6. Both ends count. range(1, 6) stops before 6.

⚡ Quick Check Flashcards4 questions
Question 1
What is a module?
Try answering before revealing!
Question 2
What is math.ceil(8.1)?
Try answering before revealing!
Question 3
Why call random.seed()?
Try answering before revealing!
Question 4
Which call finds the most common value?
Try answering before revealing!

7.9 Different ways to import modules

556 words · 3 min read

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

Python
import math

print("Square root:", math.sqrt(49))
print("Pi:", round(math.pi, 2))

Output
Square root: 7.0
Pi: 3.14

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

Python
from math import sqrt, ceil

print("Square root:", sqrt(64))
print("Ceiling:", ceil(7.1))

Output
Square root: 8.0
Ceiling: 8

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

Python
import statistics as st

scores = [5, 8, 8, 9, 10]
print("Mean:", st.mean(scores))
print("Mode:", st.mode(scores))

Output
Mean: 8
Mode: 8

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

StyleWriteCallUse when
Whole moduleimport mathmath.sqrt(25)Default. Clear and safe
Chosen namesfrom math import sqrtsqrt(25)A few names, used often
Aliasimport statistics as stst.mean(data)The module name is long
Wildcardfrom 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.

Watch out: Avoid from module import *. It dumps many names into your file and can hide your own functions.

⚡ Quick Check Flashcards4 questions
Question 1
How do you call a name after import math?
Try answering before revealing!
Question 2
What is the gain of from math import sqrt?
Try answering before revealing!
Question 3
What does as do in an import?
Try answering before revealing!
Question 4
Why skip from module import *?
Try answering before revealing!

Summary

162 words · 1 min read
  • 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.
Explain each important word in your own words. Then say why the rule works.

Exercises

517 words · 2 min read

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.

Python
def make_tag(label, code="A1"):
    print(code, label)

make_tag("Box")
make_tag("Bag", "B2")

7.4 Predict the output of this program.

Python
def add_bonus(score):
    total = score + 15
    return total

points = add_bonus(35)
print("Points:", points)

7.5 Predict what this program prints.

Python
def announce(msg):
    print("Notice:", msg)

result = announce("Meeting at noon")
print("Result is:", result)

7.6 What does this program print?

Python
points = 10

def update_points():
    points = 40
    print("Inside:", points)

update_points()
print("Outside:", points)

7.7 Predict the math-module output.

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

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

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

Python
def swap(a, b):
    return b, a

first, second = swap(10, 25)
print("first =", first, "second =", second)

7.11 What does each call print?

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

Python
def double_number(n):
    doubled = n * 2
    return doubled

double_number(8)
print(doubled)

7.13 Predict the built-in output.

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

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

Python
def first():
    print("Step 1")

def second():
    first()
    print("Step 2")

print("Start")
second()
print("End")

7.16 What does this program print?

Python
def is_even(number):
    return number % 2 == 0

print("14 is even:", is_even(14))
print("9 is even:", is_even(9))

Answers

  1. 7.1: def stores the name and the steps. A call with parentheses runs those steps.
  2. 7.2: A parameter with no default cannot follow one with a default. c needs a default too, or b must lose its default.
  3. 7.3: prints A1 Box, then B2 Bag.
  4. 7.4: Points: 50.
  5. 7.5: prints Notice: Meeting at noon, then Result is: None. announce has no return, so it yields None.
  6. 7.6: prints Inside: 40, then Outside: 10. Local points hides global points. The global value stays 10.
  7. 7.7: prints 6, then 7, then -5, then -4. floor goes toward minus infinity. ceil goes toward plus infinity.
  8. 7.8: prints 17, then 14.
  9. 7.9: prints 8, then 7, then 7. Mean is 8. Median is 7. Mode is 7.
  10. 7.10: first = 25 second = 10. Python packs a tuple and unpacks it into first and second.
  11. 7.11: prints Safe, then Normal, then Fast.
  12. 7.12: doubled is local to double_number(). After the call, that name is gone. The main program cannot read it.
  13. 7.13: prints Sum: 54, then Max: 27, then Min: 3, then Count: 4.
  14. 7.14: Final score: 75.
  15. 7.15: prints Start, then Step 1, then Step 2, then End. second() calls first() before it prints Step 2.
  16. 7.16: prints 14 is even: True, then 9 is even: False.
Up next
Continue to the next chapter