1 Functions
1 Functions
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 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.
Defining
Docstring
Body
Calling
Defining a Function 5
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.
8-1,8-2
Passing Arguments 8
Positional Arguments
Passing Arguments 9
Default Values
Passing Arguments 11
8-3,…,8-5
Return Values 14
Returning a dictionary
Return Values 16
http://pythontutor.com/
Practice 19
8-6,…,8-8
Passing a List 20
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
Note: reduce() is not a built-in function and requires importing from functools.
Map – Filter - Reduce 34
Practice 35
• 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