Overview
Teaching: 15 min
Exercises: 10 minQuestions
How can I use built-in functions?
How can I find out what they do?
What kind of errors can occur in programs?
Objectives
Explain the purpose of functions.
Correctly call built-in Python functions.
Correctly nest calls to built-in functions.
Use help to display documentation and source code for built-in functions.
Correctly describe situations in which SyntaxError and NameError occur.
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.max(1, 2, 3)
3
min('a', 'A', '0')
'0'
max
and min
must be given at least one argument.
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.
?
after a function or object to get help about it that
includes what is displayed by the Python help function.print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
Additionally IPython provides a convenient manner to view the source code of
functions. This help is available by using ??
. Most of the built-in functions
are not written in Python. For performance reasons they are written in compiled
languages like C. In these cases, the ??
help command will display the same
content as the previously mentioned help command.
print??
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
# Forgot to close the quotation marks around the string.
roi_label = 'hippocampus
...
SyntaxError: EOL while scanning string literal
# An extra '=' in the assignment.
brain_volume = = 1302
...
SyntaxError: invalid syntax
# use a multiline expression by pressing ctrl + enter after each line
brain_volume = 1302
print( brain_volume
# execute the multiline expression using shift + enter
print( brain_volume # in ipython we must execute this command using shift + enter
File "<ipython-input-408-c217d1563eb4>", line 2
print( brain_volume # in ipython we must execute this command using shift + enter
^
SyntaxError: unexpected EOF while parsing
^
pointer.brain_volume = 1302
grey_matter = 700
csf_and_white_matter = brain_volume - grey_matters # mis-spelled 'grey_matter'
NameError: name 'grey_matters' is not defined
None
.result = print('hippocampus')
hippocampus
print(result)
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(grey_matter), white_matter)
run or produce an error message? If it runs, does its result make any sense?grey_matter = "the good stuff" white_matter = "the wires" print(max(grey_matter, white_matter)) print(max(len(grey_matter), len(white_matter)))
Working with None
Why don’t
max
andmin
returnNone
when they are given no arguments?
Last Character of a String
If Python starts counting from zero, and
len
returns the number of characters in a string, what index expression will get the last character in the stringroi_label
? (Note: we will see a simpler way to do this in a later episode.)Solution
roi_label[len(roi_label) - 1]
Key Points
Use comments to add documentation to programs.
A function may take zero or more arguments.
Commonly-used built-in functions include
max
,min
, andFunctions 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 in python or ‘?’ after the function in IPython.Every function returns something.
Python reports a syntax error when it can’t understand the source of a program.
Python reports a runtime error when something goes wrong while a program is executing.
Fix syntax errors by reading the source code, and runtime errors by tracing the program’s execution.