These questions follow Subprograms and Modules. A function is a recipe with a name — write it once, use it everywhere.

Questions

  1. Predict the output — how many lines, and in what order?
    def greet(name):
        print("Hello, " + name + "!")
    greet("Ada")
    greet("Grace")
  2. Predict the output. Trace the value all the way through.
    def double(n):
        return n * 2
    print(double(5) + 1)
  3. Inside a function, how do print and return differ? One sentence each.
  4. Find the bug. This prints 5 — then crashes. Explain both.
    def add(a, b):
        print(a + b)
    total = add(2, 3) + 10
  5. Write a function area(width, height) that returns a rectangle’s area, then one line using it for a 3 by 5 rectangle.
  6. Challenge. Write is_teen(age) returning True or False, then use it in an if to decide on a movie ticket price.
  7. External modules. Using Python’s built-in random module, write a function roll_d20() that imports random, generates a random integer from 1 to 20 using random.randint(), and returns it. Then write one line calling roll_d20() and printing the result.
  8. Mathematical libraries. Write a function distance(x1, y1, x2, y2) that uses import math and math.sqrt((x2 - x1)**2 + (y2 - y1)**2) to calculate and return the straight-line distance between two 2D points. Explain why borrowing standard libraries makes your code more reliable.

Answers

Curriculum connection

C3.3

write subprograms, and use existing subprograms, to complete program components

Link to original

C3.4

write programs that make use of external or add-on modules or libraries

Link to original