Python Built-Ins#


Questions:#

  • How can I use built-in functions?

  • How can I find out what they do?

  • What kind of errors can occur in programs?

Learning 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

  • Correctly describe situations in which SyntaxError and NameError occur


Functions in Python#

  • Functions are, effectively, commands that you can run (execute) in Python.

  • Python provides many built-in functions, such as print() and len()

  • Later in this course, we will demonstrate how to write your own functions to perform specific tasks repeatedly. In this section, we will focus on understanding the basics of how functions work, and introduce a few new ones.

A function may take zero or more arguments#

An argument is a value passed into a function, inside parentheses.

  • len() takes exactly one argument

  • int(), str(), and float() take one argument

  • print takes zero or more

    • print() with no arguments prints a blank line

  • We must always use parentheses when calling a function, even if they’re empty, so that Python knows a function is being called

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

after

Every function returns something#

  • Every function call produces some result

  • If the function doesn’t have a useful result to return, it usually returns the special value None. None is a Python object that stands in anytime there is no value.

  • Somewhat counter-intuitively, print() returns None. The print() function prints its arguments directly to the output, but when we attempt to assign the result of print() to a variable, that variable ends up with a value of None:

result = print('example')
print('result of print is', result)
example
result of print is None

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

  • Use max() to find the largest value of two or more values

  • Use min() to find the smallest

  • Both work on character strings as well as numbers

    • “Larger” and “smaller” use (0-9, A-Z, a-z) to compare letters

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

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

max() and min() must be given at least two values to compare. They must also be given things that can meaningfully be compared.

See what happens when you run each of the following:

print(max(999))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 print(max(999))

TypeError: 'int' object is not iterable

max() only works if it has at least two values to compare:

print(max(999, 1000))
1000
print(max(1, 'a'))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [8], line 1
----> 1 print(max(1, 'a'))

TypeError: '>' not supported between instances of 'str' and 'int'

Since Python can’t compare int and char types, we need to give it two characters:

print(max('1', 'a'))
a

Functions may have default values for some arguments#

round() will round off a floating-point number. By default, it rounds to zero decimal places:

round(3.712)
4

We can specify the number of decimal places we want by passing a second argument

round(3.712, 1)
3.7

Errors#

You can fix syntax errors by reading the source and runtime errors by tracing execution

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

It won’t even try to run the program if it can’t be parsed.

Look more closely at this error message:

print("hello world"
  Cell In [10], line 1
    print("hello world"
                       ^
SyntaxError: unexpected EOF while parsing
  • The message indicates a problem on first line of the input (“line 1”)

    • In this case the “ipython-input” section of the file name tells us that we are working with input into IPython, the Python interpreter used by the Jupyter Notebook

  • The number after ipython-input- indicates the cell number that the error occurred in (the number in square brackets to the left of the cell). Note that cells are numbered based on the sequence they are executed in, not their order in the notebook. So if you execute the cell above again, this number will change.

  • Next is the problematic line of code, indicating the start of the problem with a ^ pointer

  • Finally, the type of error is provided on the last line

Here are some other examples of syntax errors:

# Forgot to close the quote marks around the string
name = 'Feng
  Cell In [11], line 2
    name = 'Feng
                ^
SyntaxError: EOL while scanning string literal
# An extra '=' in the assignment
age = = 52
  Cell In [12], line 2
    age = = 52
          ^
SyntaxError: invalid syntax

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

age = 53
remaining = 100 - aege # mis-spelled 'age'
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [13], line 2
      1 age = 53
----> 2 remaining = 100 - aege # mis-spelled 'age'

NameError: name 'aege' is not defined

Runtime errors are basically any type of error that is not a syntax error. The messages will provide different names for these errors, like NameError, as you just saw.

Getting Help#

Use the built-in function help to get help for a function#

Every built-in function has online documentation.

help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

Option 2:#

Type the function name in a cell with a question mark after it. Then run the cell:

round?
Signature: round(number, ndigits=None)
Docstring:
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None.  Otherwise
the return value has the same type as the number.  ndigits may be negative.
Type:      builtin_function_or_method

Option 3:#

Position your cursor over the function name and press the shift + tab keys:

# Type 'round' below and try

Putting comments in your code#

This is how you can help your future self, and others reading your code.

Anything appearing after a hash symbol # in a line of code is ignored by Python. These are called comments. This is a useful way to help yourself and other readers of your code understand what’s going on.

# This sentence isn't executed by Python
adjustment = 0.5   # Neither is this - anything after '#' is ignored

Worked example of how to evaluate a complicated expression#

Assign values to variables x and y.

# Assign values to variables
x = 5  
y = "hello"  

The key is to systematically evaluate smaller chunks of the overall expression. Below is a logical step-by-step method of interpreting what initially seems to be quite complicated. With practice, this type of mental parsing will become much easier for you.

(x > 7) or (y[0] == “h” and (x - 1) < 5)
(5 > 7) or (y[0] == “h” and (x - 1) < 5)
False or (y[0] == “h” and (x - 1) < 5)
False or (“hello”[0] == “h” and (x - 1) < 5)
False or (“h” == “h” and (x - 1) < 5)
False or (True and (x - 1) < 5)
False or (True and (5 - 1) < 5)
False or (True and 4 < 5)
False or (True and True)
False or True
True



Exercises#

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 print statements in the program below will print

  • Does max(len(rich), poor) run or produce an error message? If it runs, does its result make any sense?

easy_string = "abc"
print(max(easy_string))
rich = "gold"
poor = "tin"
print(max(rich, poor))
print(max(len(rich), poor))

Why Not?#

Why don’t max and min return None when they are given no arguments?


More on getting help: APIs#

One thing you will often find, especially if you’re trying to figure out how to use a command or function, is the application programming interface (API). The API will give you the name of the command, and the different arguments it takes. Arguments are bits of information you provide to the command (typically inside parentheses) that are either required for the command to run, or optional extra information. For example, this is the API for the NumPy (a popular Python library for data analysis and data science you will learn about later in the course) command to compute the mean of a set of numbers: numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)

The command itself is the first part before the parentheses (in this case, numpy.mean) and the arguments are in the parentheses. Each argument is separated by a comma from the other arguments. Required arguments are generally first in the list, and don’t include an = sign. The arguments with = signs are generally optional. The NumPy API at the link above also explains what each argument is; for simplicity here, the a is the set of data you want to compute the mean from (which is required; how could the function give you a mean if it didn’t have data to do that from?) and the other arguments are all options that might be required to get the result you desire.

APIs may look pretty complicated at first, but they can be very helpful in breaking down a command and understanding how to use it better. By contrast, when you search the web for answers to programming questions, often you’ll get example code that shows a particular way to use a function or method. This is also useful, but in order to adapt that to your problem (or understand what it’s actually doing), you may want to check the API for that function to learn more.


Summary of Key Points:#

  • Functions are Python commands that return a result

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

  • A function may take zero or more arguments

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

    • Functions may have default values for some arguments

  • Fix syntax errors by reading the source code, and runtime errors by tracing the program’s execution

  • Use the built-in function help to get help for a function

  • The Jupyter Notebook has two other ways to get help

    • use a ? followed by the function name

    • position cursor over command name and press the shift + tab keys

  • 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


This section was adapted from Aaron J. Newman’s Data Science for Psychology and Neuroscience - in Python, Meghan Allen’s CPSC 103 course at UBC (example of evaluating a complicated expression), and Software Carpentry’s Plotting and Programming in Python workshop.