This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 7: Using existing functions

Built-in functions

face Josiah Wang

Python provides many built-in functions. We have already used a few of these:

  • abs()
  • input()
  • print()

Now, here are some questions to help you figure out how to use some of the other built-in functions provided by Python.

You can find the complete list of built-in functions in the official documentation. The answers to the questions below can all be found on this page.

Some of the functions on the page will not make sense yet, so don’t worry. You should be able to understand them better once we have covered more topics. For now, try to find the ones you need to answer the questions below (you should be able to understand these).

Also try to see whether you can understand the documentation. You will need to know how to read and understand documentations to be able to program well, especially when you start writing more complex programs in the future.

For the questions below, write out the function call to answer the given question.

For example, for the question “Given x = -5, use a built-in function to compute the absolute value of x”, the answer should be abs(x).

Your answer might not be an exact match. It might vary in terms of spaces or order of the arguments. It is fine as long as it is valid.

Try out your answers in an interactive prompt. Experiment freely with different input arguments.

1 2 3 4 5 6 7 8

Question 1

Given x = 1.836, use a built-in function to automatically round x to the nearest integer (i.e. 2).

round(x)

Question 2

Given x = 1.836, use a built-in function to automatically round x to two decimal places (i.e. 1.84).

round(x, 2)

Question 3

What is the return value of round(0.5)?

0
Explanation:

Be careful of this Python quirk. Read the explanation in the documentation for round() carefully. round(0.5) returns 0, round(1.5) returns 2, and round(2.675, 2) gives 2.67.

Question 4

Write a function call that uses a built-in function to compute the smallest of the numbers 10, 4, and 7.

min(10, 4, 7)

Question 5

Write a function call that uses a built-in function to compute the largest of the numbers 3.5, 2.6, 7.4, and 1.8.

max(3.5, 2.6, 7.4, 1.8)

Question 6

Write a function call that uses a built-in function to compute 4^3, without using the exponentiation operator 4**3.

pow(4, 3)

Question 7

Write a function call that uses a built-in function to convert an integer 3 into its binary str representation "0b11".

bin(3)

Question 8

Given landmark = "big ben", use a built-in function to automatically compute the length of the str referenced by landmark. The length should be 7 (space is counted as a character).

len(landmark)