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

1 Functions

Chapter 2 covers the fundamentals of functions and classes, including how to define functions, pass arguments, and return values. It also introduces advanced topics such as handling arbitrary numbers of arguments, using lambda functions, and the map, filter, and reduce functions. Additionally, the chapter discusses organizing functions into modules for better code management.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

1 Functions

Chapter 2 covers the fundamentals of functions and classes, including how to define functions, pass arguments, and return values. It also introduces advanced topics such as handling arbitrary numbers of arguments, using lambda functions, and the map, filter, and reduce functions. Additionally, the chapter discusses organizing functions into modules for better code management.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 2: Functions and classes

Lecturer: Nguyen Tuan Long, Phd


Email: [email protected]
Mobile: 0982 746 235
Chapter 2: Functions and classes 2

2.1. Functions
• What are functions?
• Defining a Function
• Passing Arguments
• Return Values
• Passing a List
• Passing an Arbitrary Number of Arguments
• Modules
What are functions? 3

• Functions are named blocks of code designed to do one specific job.

• Functions allow you to write code once that can then be run whenever
you need to accomplish the same task.

• Functions can take in the information they need, and return the
information they generate.

• Using functions effectively makes your programs easier to write, read,


test, and fix.
Defining a Function 4

The simplest structure of a function

keyword The name of the function

Defining
Docstring
Body

Describes what the function does

Calling
Defining a Function 5

Passing Information to a Function

Arguments and Parameters


Parameter
Argument
Defining a Function 6

Defining a function

• The first line of a function is its definition, marked by the keyword def. The
name of the function is followed by a set of parentheses and a colon.

• A docstring, in triple quotes, describes what the function does. The body
of a function is indented one level.

• To call a function, give the name of the function followed by a set of


parentheses
Practice 7

8-1,8-2
Passing Arguments 8

Positional Arguments
Passing Arguments 9

Using keyword arguments


Passing Arguments 10

Default Values
Passing Arguments 11

Equivalent Function Calls


Passing Arguments 12

Avoiding Argument Errors


Practice 13

8-3,…,8-5
Return Values 14

Returning a Sinple Value


Return Values 15

Returning a dictionary
Return Values 16

Returning a dictionary with optional values


Return Values 17

• A function can return a value or a set of values. When a function


returns a value, the calling line should provide a variable which the
return value can be assigned to.
• A function stops running when it reaches a return statement.
Visualizing functions 18

http://pythontutor.com/
Practice 19

8-6,…,8-8
Passing a List 20

Passing a list as an argument


Passing a List 21

Allowing a function to modify a list


Passing a List 22

Preventing a function from modifying a list


Passing a List 23

Passing a list to a function


• You can pass a list as an argument to a function, and the function can
work with the values in the list.
• Any changes the function makes to the list will affect the original list.
• You can prevent a function from modifying a list by passing a copy of the
list as an argument.
Passing an Arbitrary Number of Arguments 24

• Sometimes you won't know how many arguments a function


will need to accept. Python allows you to collect an arbitrary
number of arguments into one parameter using the * operator .
• A parameter that accepts an arbitrary number of arguments
must come last in the function definition.
Collecting an arbitrary number of arguments
Passing an Arbitrary Number of Arguments 25

Collecting an arbitrary number of keyword arguments


• The ** operator allows a parameter to collect an
arbitrary number of keyword arguments.
• These arguments are stored as a dictionary with the
parameter names as keys, and the arguments as values.
Passing an Arbitrary Number of Arguments 26

Collecting an arbitrary number of keyword arguments


Order of parameters 27

1.Normal parameters
2.*args
3.Parameters have default values
4.**kwargs
Practice 28

• 8-12,…,8-14
• Exercise 1: Filter Prime Numbers using *args
Write a function that accepts n positive integers using *args to get a list of
integers. The function will return a new list containing the prime numbers
from the original list.
• Exercise 2: Student Assessment
Write a function that takes a student's name and a list of scores via
**kwargs and calculates the average of that student's scores.
Ex: student_info = {'name': 'Alice', ‘statistics': 85, ‘Pro4DS’: 90, ’ML1’: 92}
calculate_average_score(** student_info)=?
yield 29

def generate_numbers(n):
i=0
while i < n:
yield i
i += 1

def generate_numbers(n):
i=0
while i < n:
return i
i += 1
lambda 30
Map function 31

• Definition: Applies a given function to all items in an iterable (like a


list) and returns a map object (which is an iterator).
• Syntax: map(function, iterable)

# Convert a list of integers to their squares


numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16]
Filter function 32

• Definition: Filters items in an iterable based on a function that


returns either True or False.
• Syntax: filter(function, iterable)

# Filter even numbers from a list


numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0,
numbers))
print(evens) # Output: [2, 4]
Reduce function 33

• Definition: Applies a function to the first two items of an iterable


and continues applying it cumulatively to reduce the iterable to a
single value.
• Syntax: reduce(function, iterable)

from functools import reduce

# Sum of all numbers in a list


numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10

Note: reduce() is not a built-in function and requires importing from functools.
Map – Filter - Reduce 34
Practice 35

Exercise 1: Use `map()` to calculate the number of characters in each word in a


sentence.
# Input: "Python is fun to learn“
#Output: [6, 2, 3, 2, 5].
Exercise 2: Use `filter()` to remove strings that contain numbers from a list of
strings.
# Input: ['hello', 'world1', 'python', 'code123']
# Output: ['hello', 'python']
Exercise 3: Write a program using `reduce()` to find the largest number in a list
without using the `max()` function.
# Input: [5, 1, 8, 2, 9, 3]
# Output: 9
Modules 36

• You can store your functions in a separate file called a module, and
then import the functions you need into the file containing your main
program.
• This allows for cleaner program files. (Make sure your module is
stored in the same directory as your main program.)
Setting:
Google seach: “How to fix Module Not Found Error in Jupyter Notebook
(Anaconda)”
Modules 37

Storing a function in a module

Importing an entire module

Importing a specific function

Giving a module an alias

Importing all functions from a module


Don't do this, but recognize it when you see it in others' code. It can result in naming conflicts,
which can cause errors.
Practice 38

Exercise 1: Creating a Module and Using it in the Main Program


a) Create Module: Create a file named 'calculator.py' containing simple
calculation functions such as addition, subtraction, multiplication, and
division.
b) import calculator module and use calculation functions from this
module.

You might also like