Python Built-Ins#


  • 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 workshop, 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



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)
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'))

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:

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))
print(max(1, 'a'))
TypeError                                 Traceback (most recent call last)
Cell In[6], 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'))

Functions may have default values for some arguments#

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


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

round(3.712, 1)


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#

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: incomplete input
  • 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 exampels of syntax errors:

# Forgot to close the quote marks around the string
name = 'Feng
  Cell In[11], line 2
    name = 'Feng
SyntaxError: unterminated string literal (detected at line 2)
# 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

Getting Help#

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

Every built-in function has online documentation.

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.
print('Get help by clicking the print command while in edit mode, and pressing shift-tab')
Get help by clicking the print command while in edit mode, and pressing shift-tab

Option 2:#

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


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


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"
rich = "gold"
poor = "tin"
print(max(rich, poor))
print(max(len(rich), poor))

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 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 (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 lesson is adapted from the Software Carpentry Plotting and Programming in Python workshop.