Defining our Own Functions
CS 110
def name_of_function(parameters):
statement(s)
2
Keyword def marks the start of function header
A function name to uniquely identify it (snake case)
parameters (the way we pass data to a function)
colon (:) marks end of function header
function body has 1 or more statements, which have same indentation level (usually 4 spaces)
A function with inputs
Dealing with inputs to functions
Positional parameters
Keyword parameters
Need more practice writing functions?
Checkout the slides below and the example files for today!
Say Hello! (Text example of Abstraction)
# Consider the following code:
print('Hello there, Obi-wan!')
print('How are you this morning?')
Task 1 - Make this code into a function called say_hello so you can use it repeatedly.
Task 2 - Change the function so that it accepts a name as an input
Task 3 - Change the function so that the time of day is also an input.
Task 4 - Make the time of day input optional and have it default to morning
Note: all of these are in the lecture files for today if you'd like to run them in IDLE
5
# defining the function
def say_hello():
print('Hello there, Obi-wan!')
print('How are you this morning?')
# calling (invoking) the function
say_hello()
say_hello()
6
Function with no parameters
Say Hello!
def say_hello():
print('Hello there, Obi-wan!')
print('How are you this morning?')
Task 2 - Change the function so that it accepts a name as an input.
Task 3 - Change the function so that the time of day is also an input.
Task 4 - Make the time of day input optional and have it default to morning
7
# defining the function
def say_hello(name):
print('Hello there,' + name + '!')
print('How are you this morning?')
# calling (invoking) the function
say_hello('Varun')
say_hello('Grace')
8
Function with 1 positional parameter
Arguments
Parameter (positional)
Say Hello!
def say_hello(name):
print('Hello there,' + name + '!')
print('How are you this morning?')
Task 3 - Change the function so that the time of day is also an input.
Task 4 - Make the time of day input optional and have it default to morning
9
# defining the function
def say_hello(name, time_of_day):
print('Hello there,' + name + '!')
print('How are you this ' + time_of_day + '?')
# calling (invoking) the function
say_hello('Varun', 'morning')
say_hello('Grace', 'evening')
10
Function with 2 positional parameters
2 positional parameters
Arguments
Say Hello!
def say_hello(name, time_of_day):
print('Hello there,' + name + '!')
print('How are you this ' + time_of_day + '?')
Task 4 - Make the time of day input optional and have it default to morning
11
# defining the function
def say_hello(name, time_of_day='morning'):
print('Hello there,' + name + '!')
print('How are you this ' + time_of_day + '?')
# calling (invoking) the function
say_hello("Connor")
say_hello("Connor", time_of_day='evening')
12
Function with 1 keyword parameter
keyword parameter
No keyword argument (uses default)
Keyword argument overrides default