Built-in Functions and Help

Overview

Teaching: 10 min
Exercises: 5 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 for built-in functions.

  • Correctly describe situations in which SyntaxError and NameError occur.

Use comments to add documentation to programs.

# This sentence isn't executed by Python.
name = 'Library Carpentry'   # Neither is this comment - anything after '#' is ignored.

A function may take zero or more arguments.

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

after

Use the built-in function len to find the length of a string.

print(len('helium'))
6

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

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

len(obj, /)
    Return the number of items in a container.

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

# Forgot to close the quotation marks around the string.
name = 'Feng
SyntaxError: EOL while scanning string literal
# An extra '=' in the assignment.
age = = 52
SyntaxError: invalid syntax
print("hello world"
  File "<ipython-input-6-d1cc229bf815>", line 1
    print ("hello world"
                        ^
SyntaxError: unexpected EOF while parsing

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

age = 53
remaining = 100 - aege # mis-spelled 'age'
NameError: name 'aege' is not defined

Every function returns something.

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

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

Solution

name[len(name) - 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, and round.

  • Functions 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.

  • 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.