Python 101

Week 7:
Functions

Expedia Code Academy

Functions

Functions are bits of code that are reusable. This is handy because:

  • You don't have to type as much
  • It's easier to read
  • If there's a mistake you only need to fix it once!

Examples:

              # The print function with 1 argument: a string
              print("hello")
              
              # The len function with 1 argument: a list
              len([0, 1, 2, 3])
            

Creating your own functions


The syntax involves these key words: def and return

Here's a function that adds 2 number arguments together:


              def add_two_numbers(num1, num2):
                  result = num1 + num2
                  return result

              # Let's call our function!
              sum = add_two_numbers(612, 847)
            

Things to remember


Always write your function before you call it!
The below won't work - what error do you get?


              # Let's call our function!
              sum = add_two_numbers(612, 847)

              def add_two_numbers(num1, num2):
                  result = num1 + num2
                  return result
            

How about this?

                sum = add_two_numbers(612, 847, 555)
              

Different arguments


What will sum be in this example?


              def add_two_numbers(num1, num2):
                  result = num1 + num2
                  return result

              sum = add_two_numbers('my hovercraft is ', 'full of eels')
            

Exercises

  • (⭐️) 7a. Write a function that multiplies 2 numbers and returns the result
  • (⭐️⭐️) 7b. Write a function that multiplies all the numbers in a list together

  • See here for the next exercises!