Built-in Functions and Help#

Learning Objectives

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.

  • Use help to display documentation for built-in functions.

  • Correctly describe situations in which SyntaxError and NameError occur.


Comments and documentation#

You can use comments to add documentation to programs.

When coding, it is always a good idea to write comments explaining what the code does - and why.

  • Comments will help other people understand what the program does.

Just like we spoke about in regards to meaningful variable names, the most important “other person” is your future self!

# This sentence is not executed by Python.
name = 'Python for Absolute Beginners'   # Neither is this comment - anything after '#' is ignored.

Built-in functions#

A function may take zero or more arguments.

We have seen some functions already (like print() and type()) — now let us take a closer look.

  • An argument is a value passed into a function.

  • Any arguments you want to pass into a function must go into the ()

    • print("I am an argument and must go here.")

  • You must always use parentheses, because this is how Python knows you are calling a function.

    • You leave them empty if you do not want or need to pass any arguments in.

  • len() takes exactly one argument.

  • int(), str(), and float() create a new value from an existing one.

  • print() takes zero or more arguments.

    • print() prints a blank line.

print('before')
print()
print('after')
Hide code cell output
before

after

max(), min(), and round()#

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

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

  • Use min() to find the smallest value of one or more values.

  • Both work on character strings as well as numbers.

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

    • This means that:

      • 'a' is smaller than 'b'

      • 'A' is smaller than 'a'

      • '0' is smaller than 'A'

    • This is useful for ordering alphabetically.

print(max(1, 2, 3))
print(min('a', 'b', 'c'))
print(min('a', 'A'))
Hide code cell output
3
a
A

See also

To see more built-in functions, visit the Python Documentation.

Functions only work for certain arguments#

max() and min() must be given at least one argument. They must be given data types that can meaningfully be compared.

print(max(1, 'a'))
Hide code cell output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 print(max(1, 'a'))

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

The error message tells us, that we cannot compare strings and integers.

Functions have default values for some arguments#

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

round(3.712)
Hide code cell output
4

We can specify the number of decimal places we want:

round(3.712, 1)
Hide code cell output
3.7

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.

result = print('example')
print('result of print is', result)
Hide code cell output
example
result of print is None

Contrary to what we might expect, print() does not return any value as such. I carries out the execution (i.e., it prints), but after that nothing is returned. Thus, it has a return value of None.


The help() function#

Every built-in function has online documentation.

help(round)
Hide code cell output
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.

Error messages#

Syntax errors#

Python reports a syntax error when grammar rules (that is Python grammar, not English grammar) have been violated.

You have seen errors when you try to use a function incorrectly, but you can also have errors when you use punctuation incorrectly.

  • Python will run the program up until that point, but if the grammar of that line of code has produced an error, then the program will shut down with an error.

  • Error messages will try and guide you to the point, where the error happened.

  • Python error messages may vary slightly depending on your Python environment.

# Forgot to close the quotation marks around the string.
name = 'Feng
Hide code cell output
  Cell In[9], line 2
    name = 'Feng
           ^
SyntaxError: unterminated string literal (detected at line 2)
# An extra '=' in the assignment.
age = = 52
Hide code cell output
  Cell In[10], line 2
    age = = 52
          ^
SyntaxError: invalid syntax

Look more closely at the error message:

print("hello world"
Hide code cell output
  Cell In[11], line 1
    print("hello world"
                       ^
SyntaxError: incomplete input

The message indicates a problem in cell number 1 on first line of the input (“line 1”).

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

Runtime errors#

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

In Python, a runtime error is an error that occurs while a Python program is running. These errors are also known as exceptions.

Runtime errors in Python are typically caused by unexpected conditions or events that disrupt the normal flow of the program.

They can happen for various reasons, for example:

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

NameError: name 'aege' is not defined

We can:

  • Fix syntax errors by reading the source.

  • Fix runtime errors by tracing execution.


Exercises#

Exercise 1: Spot the difference#

Try to solve the two questions before you click “Show code cell output”.

  1. Predict what each of the print statements in the program below will print.

  2. Does max(len(rich), poor) run or produce an error message?
    If it runs, does its result make sense to you? (Remember that we are comparing the value of the variable and not the name of the variable.)

rich = "gold"
poor = "tin"
print(max(rich, poor))
print(max(len(rich), len(poor)))
Hide code cell output
tin
4

Exercise 2: 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 word?

word = 'blah '
word = max(min(word * 2 + 'blur ', 'aaah '), 'Ping')
print(word)
Hide code cell output
aaah 

Exercise 3: Why not?#

Why do max() and min() not return None when they are given no arguments?


Exercise 4: 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 name?

(Note: we will see a simpler way to do this in a later episode.)


Key points#

  • Use comments to add documentation to programs.

  • A function may take zero or more arguments.

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

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

  • Functions may have default values for some arguments.

  • Every function returns something.

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

  • Python reports a syntax error when it cannot understand the source of a program.

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