During the exam, ...
Define a Function with def
To define a Python function, we type def
, the function name, parentheses enclosing any input parameters to the function, and then finally, a colon (:).
Function names have the same rules as variable names (they must start with a letter or _
and contain only letters, numbers, or _
).
def do_nothing(): pass # indention is needed here
pass
statement when we want Python to do nothing.do_nothing()
function just by typing its name and parentheses. do_nothing()
Call a Function with Parentheses
def make_a_sound(): print('quack') make_a_sound()
def agree(): return True
agree()
function and test its returned value by using if
:if agree(): print('Splendid!')else: print('That was unexpected.')
Arguments and Parameters
echo()
with one parameter called anything
.return
statement to send the value of anything back to its caller twice, with a space between:def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The values we pass into the function when we call it are known as arguments.
When we call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function.
Arguments and Parameters
def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The function echo()
was called with the argument string 'Geneseo'
.
'Geneseo'
was copied within echo()
to the parameter anything
, and then returned (in this case doubled, with a space) to the caller.Arguments and Parameters
commentary
, have it take an input string parameter
called color
, and make it return the string description to its caller:def commentary(color): if color == 'red': return "It's a tomato." elif color == "green": return "It's a green pepper." elif color == 'bee purple': return "I don't know what it is, but only bees can see it." else: return "I've never heard of the color " + color + "."
Arguments and Parameters
commentary()
with the string argument 'blue'
.comment = commentary('blue')
'blue'
to the function's internal color parameterif-elif-else
logic chaincomment
.print(comment)
A function can take any number of input arguments (including zero) of any type.
It can return any number of output results (also including zero) of any type.
return
explicitly, the caller gets the result None
.def do_nothing(): passprint(do_nothing())
None
Is Useful
None
is a special Python value that holds a place when there is nothing to say.
False
, although it looks false when evaluated as a boolean. thing = Noneif thing: print("It's some thing")else: print("It's no thing")
None
from a boolean False
value, use Python's is
operator:thing = Noneif thing is None: print("It's some thing")else: print("It's no thing")
''
), lists ([]
), tuples ((,)
), dictionaries ({}
), and sets (set()
) are all False
, but are not the same as None
.==
is for value equality. It tests if two objects have the same value.
is
is for reference equality. It tests if two objects refer to the same object, i.e if they're identical.
a = [1, 2]b = ac = a[:]
a == b # True or False?a == c # True or False?a is b # True or False?a is c # True or False?
None
, True
, or False
:def whatis(thing): if thing is None: print(thing, "is None") elif thing: print(thing, "is True") else: print(thing, "is False")
whatis(None)whatis(True)whatis(False)
whatis(0)whatis(0.0)whatis('')whatis("")whatis('''''')whatis(())whatis([])whatis({})whatis(set())
whatis(0.00001)whatis([0])whatis([''])whatis(' ')
Positional Arguments
The most familiar types of arguments are positional arguments, whose values are copied to their corresponding parameters in order.
This function builds a dictionary from its positional input arguments and returns it:
def menu(wine, entree, dessert): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken', 'cake')
Positional Arguments
menu('beef', 'bagel', 'bordeaux')
Keyword Arguments
menu(entree='beef', dessert='bagel', wine='bordeaux')# Specify the wine first, but use keyword arguments for the entree and dessert:menu('frontenac', dessert='flan', entree='fish')
Specify Default Parameter Values
menu()
without the dessert
argument:def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken')
def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('dunkelfelder', 'duck', 'doughnut')
Specify Default Parameter Values
buggy()
function is expected to run each time with a fresh empty result list, add the arg argument to it, and then print a single-item list.def buggy(arg, result=[]): result.append(arg) print(result)buggy('a')buggy('b') # expect ['b']
def works(arg): result = [] result.append(arg) return resultworks('a')works('b')
def nonbuggy(arg, result=None): if result is None: result = [] result.append(arg) print(result)nonbuggy('a')nonbuggy('b')
Explode/Gather Positional Arguments with *
*
) is used inside the function with a parameter, it groups a variable number of positional arguments into a single tuple of parameter values. def print_args(*args): print('Positional tuple:', args)print_args()print_args(3, 2, 1, 'wait!', 'uh...')
*args
goes at the end and grabs all the rest:def print_more(required1, required2, *args): print('Need this one:', required1) print('Need this one too:', required2) print('All the rest:', args)print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
We can pass positional argument to a function, which will match them inside to positional parameters.
We can pass a tuple argument to a function, and inside it will be a tuple parameter.
We can pass positional arguments to a function, and gather them inside as the parameter *args
, which resolves to the tuple args.
args
to positional parameters *args
inside the function, which will be regathered inside into the tuple parameter args
:def print_args(*args): print('Positional tuple:', args)print_args(2, 5, 7, 'x')args = (2,5,7,'x')print_args(args)print_args(*args)
We can only use the *
syntax in a function call or definition.
Outside the function, *args
explodes the tuple args
into comma-separated positional parameters.
Inside the function, *args
gathers all of the positional arguments into a single args tuple.
Explode/Gather Positional Arguments with **
**
) to group keyword arguments into a dictionary, where the argument names are the keys, and their values are the corresponding dictionary values.def print_kwargs(**kwargs): print('Keyword arguments:', kwargs)print_kwargs()print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
kwargs
is a dictionary parameter.We can pass keyword arguments to a function, which will match them inside to keyword parameters.
We can pass a dictionary argument to a function, and inside it will be dictionary parameters.
We can pass one or more keyword arguments (name=value) to a function, and gather them inside as **kwargs
, which resolves to the dictionary parameter called kwargs
.
Outside a function, **kwargs
explodes a dictionary kwargs
into name=value arguments.
Inside a function, **kwargs
gathers name=value arguments into the single dictionary parameter kwargs
.
Keyword-Only Arguments
def print_data(data, *, start=0, end=100): for value in (data[start:end]): print(value)
*
in the definition above means that the parameters start
and end
must be provided as named arguments if we don’t want their default values.data = ['a', 'b', 'c', 'd', 'e', 'f']print_data(data)print_data(data, start=4)print_data(data, end=2)
def print_data2(data, *, start, end): for value in data[start:end]: print(value)print_data2(data)print_data2(data, start=4)print_data2(data, end=2)print_data2(data, start = 2, end = 4)
start
and end
are required arguments, because they doesn't have a default value and they must be specified as a keyword argument when we call the print_data2()
function.Mutable and Immutable Arguments
Remember that if we assigned the same list to two variables, we could change it by using either one? And that we could not if the variables both referred to something like an integer or a string?
If an argument is mutable, its value can be changed from inside the function via its corresponding parameter.
outside = ['one', 'fine', 'day']def mangle(arg): arg[1] = 'terrible!'outsidemangle(outside)outside
In some languages, errors are indicated by special function return values.
When we run code that might fail under some circumstances, we also need appropriate exception handlers to intercept any potential errors.
short_list = [1, 2, 3]position = 5short_list[position]
try
and except
try
to wrap your code, and except
to provide the error handling:short_list = [1, 2, 3]position = 5try: short_list[position]except: print('Need a position between 0 and', len(short_list)-1, ' but got', position)
short_list = [1, 2, 3]position = 5try: short_list[position]except: print('Need a position between 0 and', len(short_list)-1, ' but got', position)
try
block is run. except
block runs. except
block is skipped.Specifying a plain except
with no arguments, as we did here, is a catchall for any exception type.
If more than one type of exception could occur, it’s best to provide a separate exception handler for each.
We get the full exception object in the variable name if we use the form:
short_list = [1, 2, 3]while True: value = input('Position [q to quit]? ') if value == 'q': break try: position = int(value) print(short_list[position]) except IndexError as err: print('Bad index:', position) except Exception as other: print('Something else broke:', other)
IndexError
first, because that’s the exception type raised when we provide an illegal position to a sequence. It saves an IndexError
exception in the variable err
, and any other exception in the variable other
.
The example prints everything stored in other
to show what you get in that object.
3
raised an IndexError
as expected. two
annoyed the int()
function, which we handled in our second, catchall except
code.During the exam, ...
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
o | Tile View: Overview of Slides |
Esc | Back to slideshow |
During the exam, ...
Define a Function with def
To define a Python function, we type def
, the function name, parentheses enclosing any input parameters to the function, and then finally, a colon (:).
Function names have the same rules as variable names (they must start with a letter or _
and contain only letters, numbers, or _
).
def do_nothing(): pass # indention is needed here
pass
statement when we want Python to do nothing.do_nothing()
function just by typing its name and parentheses. do_nothing()
Call a Function with Parentheses
def make_a_sound(): print('quack') make_a_sound()
def agree(): return True
agree()
function and test its returned value by using if
:if agree(): print('Splendid!')else: print('That was unexpected.')
Arguments and Parameters
echo()
with one parameter called anything
.return
statement to send the value of anything back to its caller twice, with a space between:def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The values we pass into the function when we call it are known as arguments.
When we call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function.
Arguments and Parameters
def echo(anything): return anything + ' ' + anythingecho('Geneseo')
The function echo()
was called with the argument string 'Geneseo'
.
'Geneseo'
was copied within echo()
to the parameter anything
, and then returned (in this case doubled, with a space) to the caller.Arguments and Parameters
commentary
, have it take an input string parameter
called color
, and make it return the string description to its caller:def commentary(color): if color == 'red': return "It's a tomato." elif color == "green": return "It's a green pepper." elif color == 'bee purple': return "I don't know what it is, but only bees can see it." else: return "I've never heard of the color " + color + "."
Arguments and Parameters
commentary()
with the string argument 'blue'
.comment = commentary('blue')
'blue'
to the function's internal color parameterif-elif-else
logic chaincomment
.print(comment)
A function can take any number of input arguments (including zero) of any type.
It can return any number of output results (also including zero) of any type.
return
explicitly, the caller gets the result None
.def do_nothing(): passprint(do_nothing())
None
Is Useful
None
is a special Python value that holds a place when there is nothing to say.
False
, although it looks false when evaluated as a boolean. thing = Noneif thing: print("It's some thing")else: print("It's no thing")
None
from a boolean False
value, use Python's is
operator:thing = Noneif thing is None: print("It's some thing")else: print("It's no thing")
''
), lists ([]
), tuples ((,)
), dictionaries ({}
), and sets (set()
) are all False
, but are not the same as None
.==
is for value equality. It tests if two objects have the same value.
is
is for reference equality. It tests if two objects refer to the same object, i.e if they're identical.
a = [1, 2]b = ac = a[:]
a == b # True or False?a == c # True or False?a is b # True or False?a is c # True or False?
None
, True
, or False
:def whatis(thing): if thing is None: print(thing, "is None") elif thing: print(thing, "is True") else: print(thing, "is False")
whatis(None)whatis(True)whatis(False)
whatis(0)whatis(0.0)whatis('')whatis("")whatis('''''')whatis(())whatis([])whatis({})whatis(set())
whatis(0.00001)whatis([0])whatis([''])whatis(' ')
Positional Arguments
The most familiar types of arguments are positional arguments, whose values are copied to their corresponding parameters in order.
This function builds a dictionary from its positional input arguments and returns it:
def menu(wine, entree, dessert): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken', 'cake')
Positional Arguments
menu('beef', 'bagel', 'bordeaux')
Keyword Arguments
menu(entree='beef', dessert='bagel', wine='bordeaux')# Specify the wine first, but use keyword arguments for the entree and dessert:menu('frontenac', dessert='flan', entree='fish')
Specify Default Parameter Values
menu()
without the dessert
argument:def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('chardonnay', 'chicken')
def menu(wine, entree, dessert='pudding'): return {'wine': wine, 'entree': entree, 'dessert': dessert}menu('dunkelfelder', 'duck', 'doughnut')
Specify Default Parameter Values
buggy()
function is expected to run each time with a fresh empty result list, add the arg argument to it, and then print a single-item list.def buggy(arg, result=[]): result.append(arg) print(result)buggy('a')buggy('b') # expect ['b']
def works(arg): result = [] result.append(arg) return resultworks('a')works('b')
def nonbuggy(arg, result=None): if result is None: result = [] result.append(arg) print(result)nonbuggy('a')nonbuggy('b')
Explode/Gather Positional Arguments with *
*
) is used inside the function with a parameter, it groups a variable number of positional arguments into a single tuple of parameter values. def print_args(*args): print('Positional tuple:', args)print_args()print_args(3, 2, 1, 'wait!', 'uh...')
*args
goes at the end and grabs all the rest:def print_more(required1, required2, *args): print('Need this one:', required1) print('Need this one too:', required2) print('All the rest:', args)print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
We can pass positional argument to a function, which will match them inside to positional parameters.
We can pass a tuple argument to a function, and inside it will be a tuple parameter.
We can pass positional arguments to a function, and gather them inside as the parameter *args
, which resolves to the tuple args.
args
to positional parameters *args
inside the function, which will be regathered inside into the tuple parameter args
:def print_args(*args): print('Positional tuple:', args)print_args(2, 5, 7, 'x')args = (2,5,7,'x')print_args(args)print_args(*args)
We can only use the *
syntax in a function call or definition.
Outside the function, *args
explodes the tuple args
into comma-separated positional parameters.
Inside the function, *args
gathers all of the positional arguments into a single args tuple.
Explode/Gather Positional Arguments with **
**
) to group keyword arguments into a dictionary, where the argument names are the keys, and their values are the corresponding dictionary values.def print_kwargs(**kwargs): print('Keyword arguments:', kwargs)print_kwargs()print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
kwargs
is a dictionary parameter.We can pass keyword arguments to a function, which will match them inside to keyword parameters.
We can pass a dictionary argument to a function, and inside it will be dictionary parameters.
We can pass one or more keyword arguments (name=value) to a function, and gather them inside as **kwargs
, which resolves to the dictionary parameter called kwargs
.
Outside a function, **kwargs
explodes a dictionary kwargs
into name=value arguments.
Inside a function, **kwargs
gathers name=value arguments into the single dictionary parameter kwargs
.
Keyword-Only Arguments
def print_data(data, *, start=0, end=100): for value in (data[start:end]): print(value)
*
in the definition above means that the parameters start
and end
must be provided as named arguments if we don’t want their default values.data = ['a', 'b', 'c', 'd', 'e', 'f']print_data(data)print_data(data, start=4)print_data(data, end=2)
def print_data2(data, *, start, end): for value in data[start:end]: print(value)print_data2(data)print_data2(data, start=4)print_data2(data, end=2)print_data2(data, start = 2, end = 4)
start
and end
are required arguments, because they doesn't have a default value and they must be specified as a keyword argument when we call the print_data2()
function.Mutable and Immutable Arguments
Remember that if we assigned the same list to two variables, we could change it by using either one? And that we could not if the variables both referred to something like an integer or a string?
If an argument is mutable, its value can be changed from inside the function via its corresponding parameter.
outside = ['one', 'fine', 'day']def mangle(arg): arg[1] = 'terrible!'outsidemangle(outside)outside
In some languages, errors are indicated by special function return values.
When we run code that might fail under some circumstances, we also need appropriate exception handlers to intercept any potential errors.
short_list = [1, 2, 3]position = 5short_list[position]
try
and except
try
to wrap your code, and except
to provide the error handling:short_list = [1, 2, 3]position = 5try: short_list[position]except: print('Need a position between 0 and', len(short_list)-1, ' but got', position)
short_list = [1, 2, 3]position = 5try: short_list[position]except: print('Need a position between 0 and', len(short_list)-1, ' but got', position)
try
block is run. except
block runs. except
block is skipped.Specifying a plain except
with no arguments, as we did here, is a catchall for any exception type.
If more than one type of exception could occur, it’s best to provide a separate exception handler for each.
We get the full exception object in the variable name if we use the form:
short_list = [1, 2, 3]while True: value = input('Position [q to quit]? ') if value == 'q': break try: position = int(value) print(short_list[position]) except IndexError as err: print('Bad index:', position) except Exception as other: print('Something else broke:', other)
IndexError
first, because that’s the exception type raised when we provide an illegal position to a sequence. It saves an IndexError
exception in the variable err
, and any other exception in the variable other
.
The example prints everything stored in other
to show what you get in that object.
3
raised an IndexError
as expected. two
annoyed the int()
function, which we handled in our second, catchall except
code.