Ch 9 Practice: Functions

23.6. Ch 9 Practice: Functions#

Create a function called say_goodbye which displays the text “Goodbye!”

def say_goodbye():
    print("Goodbye!")

Write code that calls the function say_goodbye

say_goodbye()
Goodbye!

Redefine the function say_goodbye to take a parameter called name, and have it display “Goodbye name!” where “name” is replaced by whatever was in the name variable

def say_goodbye(name):
    print("Goodbye "+name+"!")

Write code that calls the function say_goodbye but with your name as a parameter

say_goodbye("Kyle")
Goodbye Kyle!

Try out the code below which counts from 0 to 4 slowly:

import time # We need the time library for the following examples
for i in range(5):
    print(i)
    time.sleep(1)
0
1
2
3
4

We can put that for loop in a function like this:

def counter():
    for i in range(5):
        print(i)
        time.sleep(1)

And then we can call it:

counter()
0
1
2
3
4

Now redifine counter by

  1. copying the code above which defines counter

  2. make the counter take a parameter called max

  3. Have the range call use the parameter max

def counter(max):
    for i in range(max):
        print(i)
        time.sleep(1)

Now try calling the new version of counter but passing it the argument 7

counter(7)
0
1
2
3
4
5
6

Create a function called multiply which takes two arguments, multiplies them together (*), and then returns the multiplied value

def multiply(num_1, num_2):
    return num_1 * num_2

Call the mutliply function with two numbers and save the result in a variable. Then print out the variable to see that the multiplied number was saved.

new_num = multiply(3, 5)
display(new_num)
15