Skip to main content

Unit 2 · Python mode... Activate! · Lesson 14 of 57

Function Frenzy

Okay, input time!

I have bad news.

Sorry, I lied. We aren't learning about inputs! We're learning about... functions!

Wait.... what's a function?!

A function is a block of code that runs only when you call it. I prefer the word summon, and it uses that cool teleportation trick that variables use as well!

You've actually been using a function all this time... it's called print()!

The really really nice thing about functions is that you can make your code a lot simpler and nice to read with them!

Okay, you might be confused. It might make more sense if I just show you!

"Hey Karl, make a function that adds two numbers!"

HOW DO I DO THAT????

idk man, you tell me. (Just kidding!)

All functions start with a keyword called def. Think of keywords as special words that when you type them into code, Python will do something special with them.

def is short for define, which tells Python: "Hey, I'm defining a function!"

Here's the add function in all its glory!

def add(number1, number2):
    return (number1 + number2)

Let me break down everything!

  • def - It tells Python that you are defining a function
  • add - The name of your function
  • (number1, number2) - These are your arguments. I think of them as ways to personalize what you want the function to do. We'll elaborate more on this later!
  • : - It tells Python: "Hey, I'm starting my function after this line!" (It's always the last character when you're defining a function)
  • (number1 + number2) - Python has built in math, so you can do addition (+), subtraction (-), multiplication (*), division (/), and modulus/remainder (%)!
  • return - This is a REALLY important concept, and it uses the same teleportation magic when you're printing out variables, but it's actually the one who is sending the value to you. You'll learn more about this in the next lesson.

Your turn!

Amer needs a calculator that can subtract. (Don't ask why he can't do it in his head.)

Make a function called subtract that takes two numbers, number1 and number2, and returns number1 - number2.

Use add as your cheat sheet!

Heads up: just like storing a variable, making a function doesn't print anything. If the console stays empty when you press Run, that's normal! Press Check my work to see if you got it.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.