Skip to main content

Section 9.3 Assessment: Functions

Subgoals for writing functions:.

  1. Define and initialize global variables
  2. Write function header with function name and parameters (must include () even without parameters)
    1. Optional -- Set default values for parameters
  3. Write function body
    1. Distinguish between global and local variables based on indentation
  4. Determine what to return, if anything, to call site
  5. Call function with appropriate arguments

Exercises Exercises

    1.

    Q1: Enter the output of the following program or enter “invalid” if the statement would result in an error.
    def first_func(a, b):
        return a + b * c
    
    def second_func(b, c):
        return b / c
    
    a = 10
    b = 2
    c = 6
    print(first_func(a, second_func(b, c)))
    

    2.

    Q2: How many times will the function add_variables execute in the following program?
    def add_variables(a, b):
        return a + b
    
    numbers = [6, 1, -2, 0, 2, 5, -3]
    sum = 0
    for number in numbers:
        sum = add_variables(sum, number)
        if sum > 10:
            break
    print(sum)
    

    3.

    Q3: Enter the output of the following program or enter “invalid” if the statement would result in an error.
    my_var = 10
    def update_my_var(new_val):
        my_var = new_val
    
    update_my_var(15)
    print(my_var)
    

    4.

    Q4: Enter the output of the following program or enter “invalid” if the statement would result in an error.
    def multiply(value):
        return value * 2
    
    def subtract_and_multiply(value):
        return multiply(value - 4)
    
    def divide(value):
        return value // 5
    
    val = 0
    for i in range(5):
        if i % 3 == 0:
            val = multiply(val)
        elif i % 3 == 1:
            val = divide(val)
        else:
            val = subtract_and_multiply(val)
    
    print(val)
    

    5.

    Q5: Put the code in the right order to create a program that prints all prime numbers between 1 and 30 (inclusive).
You have attempted of activities on this page.