Overview
Teaching: 10 min Exercises: 10 minQuestions
How can I use built-in functions?
How can I find out what they do?
Objectives
Explain the purpose of functions.
Correctly call built-in Python functions.
Correctly nest calls to built-in functions.
Use help to display documentation for built-in functions.
len
takes exactly one.int
, str
, and float
create a new value from an existing one.print
takes zero or more.print
with no arguments prints a blank line.
print('before')
print()
print('after')
before
after
max
, min
, and round
.max
to find the largest value of one or more values.min
to find the smallest.print(max(1, 2, 3))
print(min('a', 'A', '0'))
3
0
max
and min
must be given at least one argument.
print(max(1, 'a'))
TypeError: unorderable types: str() > int()
round
will round off a floating-point number.round(3.712)
4
round(3.712, 1)
3.7
help
to get help for a function.help(round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
shift
,
and press tab
.None
.result = print('example')
print('result of print is', result)
example
result of print is None
What Happens When
- Explain in simple terms the order of operations in the following program: when does the addition happen, when does the subtraction happen, when is each function called, etc.
- What is the final value of
radiance
?radiance = 1.0 radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
Spot the Difference
- Predict what each of the
- Does
max(len(rich), poor)
run or produce an error message? If it runs, does its result make any sense?rich = "gold" poor = "tin" print(max(rich, poor)) print(max(len(rich), len(poor)))
Why Not?
Why don’t
max
andmin
returnNone
when they are given no arguments?
Key Points
A function may take zero or more arguments.
Commonly-used built-in functions include
max
,min
, andround
.Functions may only work for certain (combinations of) arguments.
Functions may have default values for some arguments.
Use the built-in function
help
to get help for a function.The Jupyter Notebook has two ways to get help.
Every function returns something.