Chapter 4:
Functions (Python)
Lecture Slides
Chapter 4:Functions (Python) 1 / 72
Why This Chapter Matters
Functions are the main tool to:
Organize code into small, reusable blocks
Avoid repetition (DRY: Don’t Repeat Yourself)
Make programs easier to read, test, and debug
Build larger programs from smaller parts
Chapter 4:Functions (Python) 2 / 72
Learning Outcomes
After this chapter, you should be able to:
Explain what a function is and how a function call works
Use key built-in functions (e.g., type, len, max, min)
Perform type conversions with int, float, str
Import and use modules (especially math and random)
Define your own functions with def
Use parameters/arguments and return values correctly
Understand flow of execution (who calls whom)
Distinguish fruitful vs void functions
Chapter 4:Functions (Python) 3 / 72
Roadmap
1 Function calls
2 Built-in functions
3 Type conversion functions
4 Math functions (math module)
5 Random numbers (random module)
6 Adding new functions (def)
7 Definitions and uses
8 Flow of execution
9 Parameters and arguments
10 Fruitful vs void + return
11 Why functions?
12 Debugging + glossary + practice
Chapter 4:Functions (Python) 4 / 72
What Is a Function?
In programming:
A function is a named sequence of statements that performs a computation.
You call a function to run its code.
Functions can take inputs (arguments) and produce outputs (return values).
Chapter 4:Functions (Python) 5 / 72
First Example: A Function Call
type (32) # type is a built - in function
Function name: type
Argument: 32
Return value: the type/class of the argument
Chapter 4:Functions (Python) 6 / 72
Terminology: Argument and Return Value
Argument: value passed into a function as input
Return value: value produced by the function as output
Common phrase: “A function takes arguments and returns a value.”
Chapter 4:Functions (Python) 7 / 72
Mental Model of a Call
When you call a function:
1 Python evaluates the argument expressions
2 Python enters the function code
3 The function runs its statements
4 The function returns a value (or None)
5 Execution continues after the call
Chapter 4:Functions (Python) 8 / 72
Common Call Patterns
Use return value in an expression: y = f(x) + 3
Store return value: result = f(x)
Ignore return value (usually for void functions): print("Hi")
Chapter 4:Functions (Python) 9 / 72
Built-in Functions
Python provides many functions without you writing them:
Created by Python developers for common tasks
Immediately available (no import needed)
Examples: type, len, max, min, print
Chapter 4:Functions (Python) 10 / 72
max() and min() on Strings
max ( " Hello world " ) # returns the " largest " character
min ( " Hello world " ) # returns the " smallest " character
Characters are compared using their underlying ordering
In the book example, max gives ’w’ and min gives a space
Chapter 4:Functions (Python) 11 / 72
Important Warning
Treat names of built-in functions as reserved:
Avoid: max = 10 (this breaks max(...))
Avoid: list = [] (breaks list(...))
Rule: Do not reuse built-in function names as variables.
Chapter 4:Functions (Python) 12 / 72
len(): Length of a Sequence
len ( " Hello world " ) # 11 characters ( including the space )
For strings: number of characters
For lists/tuples: number of elements
Chapter 4:Functions (Python) 13 / 72
Quick Concept Check
1 What does len("abc") return?
2 What does min("abc") return?
3 Why should you avoid writing len = 5?
Chapter 4:Functions (Python) 14 / 72
Type Conversion
Python provides built-in conversion functions:
int(x): convert to integer
float(x): convert to floating point
str(x): convert to string
Used to change type when needed, especially after input.
Chapter 4:Functions (Python) 15 / 72
int(): String to Integer
int ( " 32 " ) # 32
int ( " Hello " ) # ValueError ( cannot convert )
If conversion is impossible, Python raises an error
You must validate/handle bad input in real programs
Chapter 4:Functions (Python) 16 / 72
int(): Float to Integer (Truncation)
int (3.99999) # 3 ( fraction part is chopped )
int ( -2.3) # -2 ( chops toward zero )
Not rounding — it truncates the fractional part
Chapter 4:Functions (Python) 17 / 72
float(): Integer/String to Float
float (32) # 32.0
float ( " 3.14159 " ) # 3.14159
Useful for numeric calculations requiring decimals
Chapter 4:Functions (Python) 18 / 72
str(): Convert Anything to String
str (32) # "32"
str (3.14159) # "3.14159"
Useful for combining values into messages
Chapter 4:Functions (Python) 19 / 72
Common Real Use Case: input()
input() always returns a string.
So we often do:
age = int(input("Enter age: ")) (convert to int)
rate = float(input("Enter rate: ")) (convert to float)
Chapter 4:Functions (Python) 20 / 72
Mini-Quiz: Conversion
Predict the result:
1 int("12.5")
2 float("12")
3 str(10 + 5)
4 int(-2.9)
Chapter 4:Functions (Python) 21 / 72
Modules and Imports
Some functions are not built-in; they are in modules.
A module is a file/library containing functions and variables
To use it: import the module
Chapter 4:Functions (Python) 22 / 72
Importing math
import math # load math module
print ( math ) # shows it ’s a module object
math becomes a module object
You access items using dot notation
Chapter 4:Functions (Python) 23 / 72
Dot Notation
General form:
[Link](arguments)
Examples:
[Link](2)
math.log10(1000)
[Link](radians)
Chapter 4:Functions (Python) 24 / 72
Example: log10 for Decibels
import math # import math module
ratio = signal_power / noise_power # compute signal - to - noise ratio
decibels = 10 * math . log10 ( ratio ) # log base 10 ( dB formula )
math.log10(x) computes log10 (x)
Chapter 4:Functions (Python) 25 / 72
Trigonometry Uses Radians
import math
radians = 0.7 # angle in radians
height = math . sin ( radians ) # sine of that angle
sin, cos, tan expect radians, not degrees
Chapter 4:Functions (Python) 26 / 72
Convert Degrees to Radians
import math
degrees = 45
radians = degrees / 360.0 * 2 * math . pi # convert degrees ->
radians
print ( math . sin ( radians ) ) # ~ 0.7071
[Link] provides π (approx. 15 digits accuracy)
Chapter 4:Functions (Python) 27 / 72
Verification Example
import math
print ( math . sqrt (2) / 2.0) # also ~ 0.7071
Good habit: verify results using known identities
Chapter 4:Functions (Python) 28 / 72
Common math Functions to Remember
[Link](x): square root
[Link](x): natural log (base e)
math.log10(x): log base 10
[Link](x), [Link](x), [Link](x)
[Link]: constant π
Chapter 4:Functions (Python) 29 / 72
Deterministic vs Random-Looking
Most programs are deterministic: same input → same output
Games/simulations need unpredictability
Computers often use pseudorandom numbers:
Generated by deterministic algorithms
Look random to humans
Chapter 4:Functions (Python) 30 / 72
[Link](): 0.0 to < 1.0
import random
x = random . random () # random float : 0.0 <= x < 1.0
print ( x )
Each call produces the next value in a long pseudorandom sequence
Chapter 4:Functions (Python) 31 / 72
Generate 10 Random Values (Loop)
import random
for i in range (10) : # repeat 10 times
x = random . random () # new random float each
iteration
print ( x ) # print it
Chapter 4:Functions (Python) 32 / 72
Key Idea: “Random” But Repeatable
Even though values look unpredictable:
They are generated by a deterministic algorithm
But the sequence is hard to guess without internal state
Chapter 4:Functions (Python) 33 / 72
[Link](low, high)
import random
print ( random . randint (5 , 10) ) # integer from 5 to 10 (
inclusive )
Includes both endpoints
Chapter 4:Functions (Python) 34 / 72
[Link](sequence)
import random
t = [1 , 2 , 3]
print ( random . choice ( t ) ) # randomly choose one element
Chapter 4:Functions (Python) 35 / 72
Where Random Is Used
Games: unpredictable enemy moves
Simulations: Monte Carlo methods
Sampling: pick random examples from data
Chapter 4:Functions (Python) 36 / 72
User-Defined Functions
So far we used functions written by others. Now we create our own functions:
Use the keyword def
Give the function a name
Write the indented body
Chapter 4:Functions (Python) 37 / 72
Example: A Simple Function (No Arguments)
def print_lyrics () : # function header ends
with :
print ( " I ’m a lumberjack , and I ’m okay . " ) # body line 1
print ( " I sleep all night and I work all day . " ) # body line 2
Header: def name():
Body must be indented (convention: 4 spaces)
Chapter 4:Functions (Python) 38 / 72
Header vs Body
Header: first line (name + parameters + colon)
Body: indented block of statements
If indentation is wrong, Python raises an error or behaves incorrectly.
Chapter 4:Functions (Python) 39 / 72
Calling Your Function
def print_lyrics () :
print ( " I ’m a lumberjack , and I ’m okay . " )
print ( " I sleep all night and I work all day . " )
print_lyrics () # function call
Defining a function does not run its body
The body runs only when called
Chapter 4:Functions (Python) 40 / 72
Functions Can Call Functions
def print_lyrics () :
print ( " I ’m a lumberjack , and I ’m okay . " )
print ( " I sleep all night and I work all day . " )
def repeat_lyrics () :
print_lyrics ()
print_lyrics ()
repeat_lyrics ()
Chapter 4:Functions (Python) 41 / 72
Definition vs Use
Definition: creates the function object
Use (call): executes the function body
Critical rule: A function must be defined before it is called.
Chapter 4:Functions (Python) 42 / 72
Common Beginner Mistake
Calling a function before Python has executed its definition:
Leads to NameError (function name not known yet)
Fix: move function definitions above the first call.
Chapter 4:Functions (Python) 43 / 72
Flow of Execution
Flow of execution = order in which statements run:
Program starts at top of the file
Runs line by line
A function call is a detour:
jump into function body
return back after completion
Chapter 4:Functions (Python) 44 / 72
Function Call Detour (Diagram)
Main program
Call function()
Function body runs
Return to main
Chapter 4:Functions (Python) 45 / 72
Nested Calls
One function can call another:
main() calls A()
A() calls B()
B() returns to A()
A() returns to main()
Python tracks where to return automatically.
Chapter 4:Functions (Python) 46 / 72
Parameters vs Arguments
Argument: value passed in at the call site
Parameter: variable inside function that receives the value
Think: argument is the actual value; parameter is the placeholder name.
Chapter 4:Functions (Python) 47 / 72
Example: One Parameter
def print_twice ( bruce ) : # bruce is a parameter
print ( bruce ) # prints parameter value
print ( bruce ) # prints again
print_twice ( " Spam " ) # " Spam " is an argument
print_twice (17) # 17 is an argument
Chapter 4:Functions (Python) 48 / 72
Key Insight: Names Don’t Need to Match
Caller variable name does not matter:
michael = "Eric"
print_twice(michael)
Inside the function, the parameter might be named bruce.
Chapter 4:Functions (Python) 49 / 72
Arguments Can Be Expressions
import math
print_twice ( " Spam " * 4) # expression evaluated once
print_twice ( math . cos ( math . pi ) ) # nested function calls
Arguments are evaluated before the function runs
Chapter 4:Functions (Python) 50 / 72
Two Kinds of Functions
Fruitful function: returns a value
Void function: performs an action, returns no useful value
Examples:
Fruitful: [Link](5)
Void: print("Hello")
Chapter 4:Functions (Python) 51 / 72
Using Fruitful Functions
You almost always do something with a return value:
Store it: x = [Link](radians)
Use in expression: golden = ([Link](5)+1)/2
Chapter 4:Functions (Python) 52 / 72
Void Functions Return None
def print_twice ( x ) :
print ( x )
print ( x )
result = print_twice ( " Bing " ) # returns None
print ( result ) # prints None
None is a special value of type NoneType
Chapter 4:Functions (Python) 53 / 72
return Statement
To return a value from a function:
compute result
use return result
Without return, a function returns None.
Chapter 4:Functions (Python) 54 / 72
Example: addtwo(a, b)
def addtwo (a , b ) : # two parameters
added = a + b # compute sum
return added # send value back to caller
x = addtwo (3 , 5) # function call returns 8
print ( x ) # prints 8
Chapter 4:Functions (Python) 55 / 72
Tracing addtwo() Execution
Call: addtwo(3,5)
1 a gets 3, b gets 5 (parameters assigned)
2 added becomes 8
3 return added sends 8 back
4 caller stores it in x
Chapter 4:Functions (Python) 56 / 72
Why Divide Programs into Functions?
Key reasons:
Readability: name a block of logic
Reusability: call it many times
Maintainability: change code in one place
Debugging: test parts separately
Chapter 4:Functions (Python) 57 / 72
Design Principle: One Clear Job
A good function:
Does one clear task
Has a meaningful name
Uses parameters for input
Returns a useful result (if fruitful)
Chapter 4:Functions (Python) 58 / 72
Debugging: Indentation and Whitespace
Common issues:
Tabs vs spaces can cause errors
Prefer spaces only (most editors do this automatically)
Body of def must be properly indented
Chapter 4:Functions (Python) 59 / 72
Debugging: Make Sure You Run the Right File
Tips:
Save your file before running
If unsure, add print("hello") at top and run
If you don’t see it, you are not running the file you think you are
Chapter 4:Functions (Python) 60 / 72
Glossary (1/2)
argument: value passed into a function call
parameter: name inside function for the passed value
function definition: code that creates a function (def)
function call: code that runs a function (name(...))
return value: value produced by a function
Chapter 4:Functions (Python) 61 / 72
Glossary (2/2)
module: library containing code/data (e.g., math)
dot notation: [Link]
fruitful function: returns a value
void function: returns no useful value (None)
flow of execution: order statements actually run
Chapter 4:Functions (Python) 62 / 72
Practice 1: Multiple Choice (Concept)
What is the purpose of the def keyword in Python?
1 It prints a definition
2 It indicates the start of a function definition
3 It stores an indented block for later execution
4 (b) and (c) are both true
Chapter 4:Functions (Python) 63 / 72
Answer (Practice 1)
Correct answer: (d)
def starts a function definition
The indented body is stored and runs later when called
Chapter 4:Functions (Python) 64 / 72
Practice 2: Predict Output
Predict the output:
def fred () :
print ( " Zap " )
def jane () :
print ( " ABC " )
jane ()
fred ()
jane ()
Chapter 4:Functions (Python) 65 / 72
Answer (Practice 2)
Output:
ABC
Zap
ABC
Chapter 4:Functions (Python) 66 / 72
Practice 3: Write computepay(hours, rate)
Write a function computepay(hours, rate):
If hours > 40, overtime is time-and-a-half
Return the pay
Chapter 4:Functions (Python) 67 / 72
Solution (Practice 3) with Comments
def computepay ( hours , rate ) : # define function with 2
parameters
if hours <= 40: # case 1: no overtime
pay = hours * rate # regular pay
else : # case 2: overtime
exists
regular = 40 * rate # pay for first 40 hours
overtime_hours = hours - 40 # hours beyond 40
overtime = overtime_hours * rate * 1.5 # overtime pay at
1.5 x
pay = regular + overtime # total pay
return pay # return the computed
pay
Chapter 4:Functions (Python) 68 / 72
Practice 4: Write computegrade(score)
Write computegrade(score):
score ≥ 0.9 → A
score ≥ 0.8 → B
score ≥ 0.7 → C
score ≥ 0.6 → D
else F
Also handle invalid input (not numeric or out of range).
Chapter 4:Functions (Python) 69 / 72
Solution (Practice 4) with Comments
def computegrade ( score ) : # define function for
grading
if score < 0.0 or score > 1.0: # validate range
return " Bad score " # return error message
if score >= 0.9: # check A boundary
return " A " # return grade A
elif score >= 0.8: # check B boundary
return " B " # return grade B
elif score >= 0.7: # check C boundary
return " C " # return grade C
elif score >= 0.6: # check D boundary
return " D " # return grade D
else : # otherwise below 0.6
return " F " # return grade F
Chapter 4:Functions (Python) 70 / 72
How to Use computegrade() Safely
s = input ( " Enter score : " ) # read input as string
try :
score = float ( s ) # attempt conversion to
float
print ( computegrade ( score ) ) # call function and
print grade
except :
print ( " Bad score " ) # handle non - numeric
input
Chapter 4:Functions (Python) 71 / 72
Wrap-Up
You should now be confident with:
Calling functions and using return values
Built-in functions (len, max, min, type)
Type conversions (int, float, str)
Using modules (math, random) with dot notation
Defining functions with def
Parameters vs arguments
Fruitful vs void functions and return
Chapter 4:Functions (Python) 72 / 72