0% found this document useful (0 votes)
7 views

2B Slides

Uploaded by

miranda20060618
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

2B Slides

Uploaded by

miranda20060618
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CSC110 WEEK 2B:

DEFINING FUNCTIONS
Sadia Sharmin, Department of Computer Science

Navigation tip for web slides: press ? to see keyboard navigation controls.
RECAP
STORY SO FAR
So far in this course, we’ve learned about:
seven core data types
int, float, bool, str, set, list, dict
literals for these data types
e.g., 3, 'hello', [1, 2, 3]
operators that can combine values
e.g., +, and, in
variables and assignment statements to store values
e.g., numbers = {1, 2, 3}
comprehension expressions to transform collections
e.g. {x ** x for x in numbers}
built-in functions to perform more computations
e.g., abs, sum, sorted, help
STORY SO FAR
The elements of code we’ve seen so far are the building blocks of
computation.
Today, we’re going to learn how to combine these elements to write
code that solves real problems—by defining our own functions.
LEARNING OBJECTIVES
In this part of this week’s lectures, you will learn to:
1. Recognize and write Python code for function definitions.
2. Define your own Python functions by applying the different forms
of Python code you’ve learned so far.
3. Follow the steps of the Function Design Recipe when writing
Python functions.
4. Define the term method and identify and use various Python
methods.
DEFINING OUR OWN
PYTHON FUNCTIONS
CUSTOM-MADE FUNCTIONS
You can make your own functions in Python!
And then you can call them multiple times.
Saves you from annoying, repetitive code.
HOW DO WE DO THIS?
In math, we can define our own mathematical functions just by
writing them down:

f : R → R

2
f (x) = x

How do we define our own functions in the Python programming


language?
PYTHON FUNCTION SYNTAX
Note that you section off the code that is part of the function
through indentation (indentation is extremely important in Python).

def function_name():
# all code that belongs to the function
# is indented in this block
ANATOMY OF A FUNCTION DEFINITION
f : R → R

2
f (x) = x

def square(x): def square(x: float) -> fl


return x ** 2 """Return x squared.

>>> square(3.0)
9.0
>>> square(2.5)
6.25
"""
return x ** 2
PARTS OF A FUNCTION DEFINITION (1)
The first line is the function header:

def square(x: float) -> float:

The function header includes:


1. The keyword def, indicating the start of a function definition.
2. The function name.
square
3. The parameter name(s) and parameter type(s).
x: float
4. The return type.
float
5. A final :, indicating the end of the function header.
PARTS OF A FUNCTION DEFINITION (2)
The part in triple-quotes is the function docstring.

"""Return x squared.

>>> square(3.0)
9.0
>>> square(2.5)
6.25
"""

The function docstring contains:


1. A plain English description of what the function does.
2. Examples of function call expressions in the Python console.
PARTS OF A FUNCTION DEFINITION (3)
The code under the docstring is the function body. This is the code
that is executed when the function is called.

return x ** 2
RETURN STATEMENTS
New statement type: return statement.

return <expression>

Return statements can only appear in the body of a function—can’t


type into Python console directly!
When the Python interpreter executes a return statement:
1. It evaluates the <expression>.
2. It stops executing code in the function body, and returns the value
from Step 1.
NOTE: DEFINITION VS. CALL
When you first define a
function, that’s all you’re doing:
defining it
The code inside the function
doesn’t actually get executed
until you call the function.
How do you call a function?
Just write it’s name, and pass
in values that it needs as
parameters, if any (same way
you call built-in functions).
NOTE: DEFINITION VS. CALL
def square(x):
return x ** 2

So, the above defines the function.


Now, to use it with a specific value, we do something like:
square(3)
EXERCISE 1: REVIEWING THE PARTS OF
A FUNCTION DEFINITION
DEMO: WRITING CODE IN A PYTHON FILE
New form of syntax error: IndentationError

def square(x: float) -> float:


"""Return x squared.

>>> square(3.0)
9.0
>>> square(2.5)
6.25
"""
return x ** 2
THE FUNCTION DESIGN
RECIPE
The Function Design Recipe is a structured process for taking a
problem description and designing and implementing a Python
function to solve that problem.
1. Write examples uses
2. Write the function header
3. Write the function description
4. Implement the function body
5. Test the function
WORKED EXAMPLE
Problem: given four floats representing the coordinates of two
points (x , y ) and (x , y ), calculate the distance between the two
1 1 2 2

points, rounded to 1 decimal place.


Recall the distance formula from mathematics:

2 2
d = √ (x2 − x1) + (y2 − y1)
1. WRITE EXAMPLE USES
Goal: make sure you understand what the function is supposed to
do.
2. WRITE THE FUNCTION HEADER
Goal: formalize the function’s name, parameters, and type contract.
(Note: By default, the type contract is not enforced by Python. It just
acts as part of the documentation for humans to learn about your
function.)
3. WRITE THE FUNCTION DESCRIPTION
Goal: make sure you understand what the function is supposed to
do, and explain it clearly in plain English (avoid going into details
about the code; describe what the function does, not how it does it.).
SOME NOTES ABOUT THE DESCRIPTION
The docstring description should be short and concise.
Tips on writing good docstring descriptions:
Describe precisely what the function does, but do NOT reveal how
the function does it (don’t talk about code implementation details)
Make the purpose of every parameter clear; often, docstrings will
refer to every parameter by their name
Be clear about whether the function returns a value and, if it does,
what it returns
Write the description as a command (e.g. Return the first …) rather
than a statement (e.g. Returns the first …)
4. IMPLEMENT THE FUNCTION BODY
Goal: write the code to make the function do what it’s supposed to
do.
5. TEST THE FUNCTION
Goal: make sure you did the previous four steps correctly, and make
changes if necessary.
EXERCISE 2: FUNCTION DESIGN
PRACTICE
NOTES ABOUT FUNCTION DESIGN (1)
Writing example uses, the function header, and function description
serves two purposes:
1. Confirm your own understanding of what the function is
supposed to do.
2. Communicate to others what the function is supposed to do
(recall help – this works on our own functions too, to show you
the function header and docstring that you wrote).
Don’t skip these steps!
NOTES ABOUT FUNCTION DESIGN (2)
There are multiple ways of implementing a function.

def after_tax_cost_total(products: list, tax_rate: float) -> floa

return sum(prices) * (1 + tax_rate)

return sum(prices) + sum(prices) * tax_rate

return after_tax_cost(sum(prices), tax_rate)

return sum([price * (1 + tax_rate) for price in prices])

return sum([after_tax_cost(price, tax_rate) for price in pric


METHODS
STORY SO FAR
Recall some built-in Python functions:

>>> abs(-5) >>> abs(-5.5)


5 5.5
>>> len([10, 20, 30]) >>> len('David is cool')
3 13
>>> sorted({-5, 10, -999}) >>> sorted([-5, 10, -999])
[-999, -5, 10] [-999, -5, 10]
>>> type('hi') >>> type({'hi': 13})
<class 'str'> <class 'dict'>

The built-in Python functions we’ve studied so far all work on


multiple data types.
DATA-TYPE-SPECIFIC FUNCTIONS
A method is a function that has been defined for a specific data type.
Demo:
str.lower
str.split
set.union
list.count

A method is a specific type of function. All methods are


functions, but not all functions are methods.
FUNCTIONS VS. METHODS
A method is a function that has been defined for a specific data type.
str.lower, str.split, set.union, …

A top-level function is a function that is not a method.


abs, sorted, type, help, …

All of the functions we’ve defined ourselves so far have been top-
level functions. We’ll learn much later this semester how to define
new methods.
OBJECT-DOT NOTATION
The standard way of calling methods is to have Python figure out
the data type of the object rather than explicitly writing the type
(e.g. str., list.) out yourself.

This notation moves the object we want to execute the method on to


the beginning of the method call, like so: list.append(lst, 10)
can be written as lst.append(10), and str.lower(s) as simply
s.lower().

More generally, our method calls of the form


type(obj).method(obj, arg1, arg2, ..., argn)

can be shortened to obj.method(arg1, arg2, ..., argn)


EXERCISE 3: PRACTICE WITH METHODS
(FINISH THIS FOR HOMEWORK)
SUMMARY
TODAY YOU LEARNED TO…
1. Recognize and write Python code for function definitions.
2. Define your own Python functions by applying the different forms
of Python code you’ve learned so far.
3. Follow the steps of the Function Design Recipe when writing
Python functions.
4. Define the term method and identify and use various Python
methods.

You might also like