Skip to main content

Section 9.2 WriteFunction-WE1-P1

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: Put the code in the right order to create a program that generates a random number between 0 and 10 as a global variable, and then calls a function that takes no arguments to print out the square and the cube of that variable.

2.

Q2: Put the code in the right order to create a program that defines a function called calculate_celsius that returns the temperature in Celsius given a temperature in Fahrenheit. This function can optionally round the temperature in Celsius. Prompt the user for a temperature in Fahrenheit, and then use the calculate_celsius function to print out a message with the temperature in Celsius.

3.

Q3: Put the code in the right order to create a program that takes 2-3 numbers and returns the summation of those numbers. The default value for the third input is set to a global variable called DEFAULT_VALUE, which is defined at the top of the program as a random number between -10 and 10. If DEFAULT_VALUE is greater than 0, call the function with the values 3 and 5 and no third parameter and print out the result. Otherwise, call the function with the values 2 and 8 and the third parameter as 5, and print a message saying “Not using default value” and then print the result.

4.

Q4: Put the code in the right order to create a program that prints the sum and the average of a list of numbers.

5.

Q5: Given the following code, write a single line of python that will print out the result of the equation 6 * (3 + 2)
def sum(a, b):
    return a + b

def multiply(a, b):
    return a * b
You have attempted of activities on this page.