Consider a program that prints a $5 shipping charge for products on a website:
print("You've purchased a Hanging Planter.")print("Thank you for your order. There will be a $5.00 shipping charge for this order.")# 10 minutes later...print("You've purchased a Shell Mirror.")print("Thank you for your order. There will be a $5.00 shipping charge for this order.")# 5 minutes later...print("You've purchased a Modern Shag Rug.")print("Thank you for your order. There will be a $5.00 shipping charge for this order.")
What if there are 1,000 orders?
Functions
We can write a function to print the order.
A function is simple—it's a reusable piece of code. We only define it once. Later, we can use its name as a shortcut to run that whole chunk of code.
Functions are defined using the def syntax.
def stands for "define."
In this case, we're defining a function named 'function_name.'
deffunction_name():# What you want the function to do# Call the function by name to run it:function_name()# 10 minutes later...function_name()
Protip: Don't forget the (), and be sure to indent!
Seeing Functions in Action
So we define the function, then we can call the function by pairing its name with the parenthesis: print_order().
Naming a Function
What can you name a function?
Anything you'd like.
But match the callback!
Using print_order is more descriptive.
What do you think will happen if you change the function name print_order to finishedOrder without updating the callback?
Let's write a function together, high_low, that prints "High!" if a variable my_number is greater than 10 and "Low!" if it isn't.
You Do: FizzBuzz
This is a very common programming question. It's often on job interviews and a buzzword in the industry as a simple but common task to show your understanding.
Open a new Python file, fizzbuzz.py.
Write a program that prints the numbers from 1 to 101.
But, for multiples of three, print “Fizz” instead of the number.
For multiples of five, print “Buzz”.
For numbers which are multiples of both three and five, print “FizzBuzz”.
Quick Review: Functions
Functions are reusable chunks of code. They can have anything in them.
Define functions using the def keyword.
A function must be called before the code in it will run!
You will recognize function calls by the () at the end.
# This part is the function definition!defsay_hello():print("hello world!")# This part is actually calling/running the function!say_hello()
You can call them as many times as you'd like, but they need to be defined above the code where you call them.
Up next: Parameters!
Discussion: Parameters
Remember this?
defprint_order():print("Thank you for your order. There will be a $5.00 shipping charge for this order.")print("You've purchased a Hanging Planter.")print_order()print("You've purchased a Shell Mirror.")print_order()print("You've purchased a Modern Shag Rug.")print_order()
There's still repetition. How do you think we could improve it?
Addressing the repetition
We can dynamically pass a function values. This is a parameter.
defprint_order(product):print("Thank you for ordering the",product,".")print_order("Hanging Planter")# Prints "Thank you for ordering the Hanging Planter."print_order("Shell Mirror")# Prints "Thank you for ordering the Shell Mirror."print_order("Modern Shag Rug")# Prints "Thank you for ordering the Modern Shag Rug."
Terminology Recap
Parameter: The variable that's defined in a function's declaration.
Argument: The actual value passed into the function when the function is called.
defmy_function(parameter):# Does something.my_function(argument)
Case of the Missing Argument
What happens if you do this incorrectly?
Try removing "Hanging Planter" from the code so print_order is called with an empty parenthesis. Hit Run.
Partner Exercise: Thanks a Latte
Pair up! Decide who will be the driver and who will be the navigator.
Imagine that you are tasked with creating a program to calculate the total amount, including sales tax, for each item at a coffee shop.
Create a new file, latte.py, and type the two functions below into it, which will calculate the total amount for two drinks:
Pro tip: Don't just copy! Typing will be good practice.
---
Partner Exercise: Thanks a Latte
deflatte_total():price=5.50sales_tax_rate=.10total_amount=price+(price*sales_tax_rate)print("The total is $",total_amount)latte_total()defamericano_total():price=4.75sales_tax_rate=.10total_amount=price+(price*sales_tax_rate)print("The total is $",total_amount)americano_total()
Keep it DRY (Don't Repeat Yourself)
But what if we have several drinks at the coffee shop?
With your partner, think about a function that could print the total of any drink if you pass it the price, like this...
defcalculate_total(price):#your code herecalculate_total(5.5)# This was the lattecalculate_total(4.75)# This was the Americano
Your task: Write this!
Latte: Solution
How did it go?
Is this close to yours?
defcalculate_total(price):sales_tax_rate=.10total_amount=price+(price*sales_tax_rate)print("The total is $",total_amount)calculate_total(5.5)# This will print 6.05.calculate_total(4.75)# This will print 5.225.
Multiple Parameters: Part 1
What about changing sales tax? We can pass as many values into the function as we want - we can have as many parameters as we want.
Here, we have a second parameter, taxes:
defcalculate_total(price,taxes):total_amount=price+(price*taxes)print("The total is $",total_amount)calculate_total(5.5,.10)# "price" is 5.5; "taxes" is .10. This will print 6.05.calculate_total(4.75,.12)# "price" is 4.75; "taxes" is .12. This will print 5.32.
Protip: Use a comma-separated list — (parameter1, parameter2, parameter3, parameter4)
Multiple Parameters: Part 2
With parameters, order matters! Programs don't automatically understand what should go where - they assign values in order.
Partner Exercise: Functions With Logic
With the same partner, switch drivers. You can use the same file or start a new one.
Let's go back to our shipping example. Depending on the order amount, our user might get free shipping, so the print statement is different.
Use this starter code, which works for one product. Can you build a function from it that works for any product and order_amount?
product="Hanging Planter"order_amount=35print("Thank you for ordering the Hanging Planter.")iforder_amount>=30:print("It's your lucky day! There is no shipping charge for orders over $30.00.")else:print("There will be a $5.00 shipping charge for this order.")
Hint: You can put any code you'd like inside a function.
Reminder: Don't forget to indent!
Quick Review: Functions with Parameters
Parameter: The variable that's defined in a function's declaration.
Argument: The actual value passed into the function when the function is called.
Order matters!
defdo_something(parameter1,parameter2):# Does something.do_something(argument1,argument2)do_something(a_different_argument_1,a_different_argument_2)
Next up: Returns.
The Return
Sometimes, we want values back from functions.
defcalculate_total(price,taxes):total_amount=price+(price*taxes)print'The total is $',total_amount# Send the total_amount for the drink back to the main program.returntotal_amount# This just calls the function - we've seen this.calculate_total(5.5,.10)# This is new! Save the amount of this drink into a variable "latte_total."latte_total=calculate_total(5.5,.10)# Now, we can use that variable.print'Your order total is',latte_total
total_amount is returned to the main program.
The value in total_amount is saved as latte_total.
We Do: Practicing Returns
Let's fill this in together:
Define a function, add_two, that takes a parameter number.
It adds 2 to number, saving that in a new variable, total; print total out. Then, return total.
Discussion: Return Statements With Logic
The return statement exits a function, not executing any further code in it. What do you think the following will print?
We can also use return by itself as a way to exit the function and prevent any code that follows from running.
defrock_and_roll(muted):song="It's only Rock 'N' Roll"artist="Rolling Stones"if(muted==True):return# Here, we use return as a way to exit a function# We don't actually return any value.print("Now playing: ",song," by ",artist)rock_and_roll(True)
Quick Knowledge Check
Looking at this code, where will the function stop if x is 10?
Get with a partner. Decide who will drive and who will navigate.
In a new local file, write a function, copy_list, that takes in a list, original_list, as a parameter. Your function should create a new list, my_new_list with the contents of the original list. Your function should return my_new_list.
Example:
my_list=[1,2,3]my_new_list=copy_list(my_list)print(my_new_list)# Will print [1, 2, 3]
Hint: you'll need to declare my_new_list above (outside of) your for loop.
Make sure you run your function to check!
Partner Exercise: Reversing a List
With the same partner, switch driver and navigator.
In a local file (it can be the same one, if you'd like), write a function, reverse_list, that takes in a list, my_list, as a parameter. Your function should reverse the list in place and return it.
Example:
my_list=[1,2,3]reversed_list=reverse_list(my_list)print(reversed_list)# Will print [3, 2, 1]
Make sure you run your function to check!
You Do: Reversing a List
Now, work on your own.
In a local file, write a function, check_list_equality, that takes in two lists, first_list and second_list, as parameters. Your function should return True if the two lists contain the same elements in the same order. Otherwise, it returns False.