Python Programming: Functions


Learning Objectives

After this lesson, you will be able to…

  • Identify when to use a function.
  • Create and call a function with arguments.
  • Return a value from a function.

Let’s Consider a Repetitive program…

Consider a program that prints a $5 shipping charge for products on a website:

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.’

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?


Multi-Line Functions

How many lines of code can a function have? - As many lines of code as you’d like! - Just indent each line.


We Do: Writing a Function

Let’s make this a little more complicated.

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.

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?

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.


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.


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


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…

Your task: Write this!


Latte: Solution

How did it go?

Is this close to yours?


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:

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?

  • 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!

Next up: Returns.


The Return

Sometimes, we want values back from functions.

  • 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?


Discussion: What Will Happen?

What do you think will print out?


Exiting a Function

We can also use return by itself as a way to exit the function and prevent any code that follows from running.


Quick Knowledge Check

Looking at this code, where will the function stop if x is 10?


Another Knowledge Check

Take this simple adder function:

Which of the following statements will result in an error?

A. adder(10, 100.)
B. adder(10, '10')
C. adder(100)
D. adder('abc', 'def')
E. adder(10, 20, 30)


Quick Review: Return Statements

Return statements allow us to get values back from functions:

Return statements also exit the function - no further code in the function happens!


Partner Exercise: Building a Copy

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:

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:

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.

Example:

Hint: Start by just making sure the lists have the same length!

Hint: You’ll only need one for loop.


Summary + Q&A:

Can you now:

  • Identify when to use a function?
  • Create and call a function with arguments?
  • Return a value from a function?