These questions follow Functions and Parameters, Returns, and Scope. A function is a named piece of thinking: information goes in through parameters, an answer comes back through return, and everything else stays inside.

Reading

  1. In def letter_grade(mark):, called as letter_grade(78), name these four things: the definition, the parameter, the argument, and what return "B" does.
  2. Predict the output.
    def double(number):
        print(number * 2)
     
    result = double(5)
    print(result)
  3. Find the fault. This is supposed to give 69.5.
    def average(values):
        total = 0
        for value in values:
            total = total + value
        total / len(values)
     
    print(average([78, 91, 46, 63]))
  4. Why does this fail, and what should the last line be instead?
    def total_of(values):
        total = 0
        for value in values:
            total = total + value
        return total
     
    total_of([1, 2])
    print(total)

Writing

  1. Write kilograms_to_pounds(kilograms), which returns the mass in pounds (multiply by 2.2). Print the result for 6.5 kg to one decimal place.
  2. Write is_overdue(days_late), which returns True or False. Show it being used directly inside an if.
  3. Write greet(name, greeting="Hello") so that greet("Priya") and greet("Priya", "Welcome back") both work.
  4. Challenge. These two lines appear in four places in a program:
    hours = minutes // 60
    rest = minutes % 60
    Turn them into a function, then write a second function that uses the first to produce Priya: 3 h 5 min.

Answers