Open and Reproducible Neuroscience

Built-in Functions and Help

Overview

Teaching: 15 min
Exercises: 10 min
Questions
  • 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.

A function may take zero or more arguments.

print('before')
print()
print('after')
before

after

Commonly-used built-in functions include max, min, and round.

max(1, 2, 3)
3
min('a', 'A', '0')
'0'

Functions may only work for certain (combinations of) arguments.

max(1, 'a')
TypeError: unorderable types: str() > int()

Functions may have default values for some arguments.

round(3.712)
4
round(3.712, 1)
3.7

Use the built-in function 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.

IPython provides easier access to help

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

Python reports a syntax error when it can’t understand the source of a program.

# 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

Python reports a runtime error when something goes wrong while a program is executing.

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

Every function returns something.

result = print('hippocampus')
hippocampus
print(result)
None

What Happens When

  1. 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.
  2. 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

  1. Predict what each of the print statements in the program below will print.
  2. 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 and min return None 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 string roi_label? (Note: we will see a simpler way to do this in a later episode.)

Solution

roi_label[len(roi_label) - 1]

Key Points