โ† Back to Python Course
๐Ÿ› ๏ธ Functionsยท20 minยทIntermediate
๐ŸŽฏ

Defining Functions

Make your own commands!

Learn how to create your own functions โ€” reusable blocks of code that you can call whenever you need them.

๐Ÿ“–

What we are learning

A function is a named block of code that does a specific job. You define it once, then call it by name whenever you want it to run. Functions help you avoid repeating code and keep your programs organized.

๐Ÿ’ก Think of it like this:

Think of a function like a recipe card. You write the recipe once (define the function), and then anytime you want that dish, you just follow the card (call the function). You do not rewrite the recipe every time!

๐ŸŒŸ

Why it matters

Functions are the building blocks of real programs. Every app you use is made of hundreds or thousands of functions. Learning to write them is a huge step forward!

Where you see this in real life:

  • โœ“Games have functions for moving, jumping, and scoring
  • โœ“Calculator apps have functions for each operation
  • โœ“Websites have functions for logging in, searching, and displaying content
๐ŸŽฏ

By the end, you can:

  • 1.Define a function with def
  • 2.Call a function by its name
  • 3.Understand function scope
๐Ÿ”ค

New words

deffunctioncallparameterargument
๐Ÿ
If you could create a magic command that does one thing for you automatically, what would it do?
๐Ÿค“

Fun Fact!

The print() function you have been using is just a built-in function! Someone at Python HQ wrote it so you do not have to.

๐ŸŽฏ Make Your Own Commands!

A function is a named block of code that does a specific job. You define it once, then call it by name whenever you want it to run. Functions help you avoid repeating code and keep your programs organized.

โœจ Define and Call a Function

Use the defkeyword to create a function. Then call it by writing its name with parentheses!

๐ŸDefine and call a function
main.py
โ— Output
def creates the function. Calling it by name runs the code inside.

๐Ÿ’ก We called the function 3 times โ€” but only wrote the code once!

๐ŸŽจ Functions with Actions

Functions can do anything โ€” print, calculate, make decisions, loop, and more!

๐ŸFunctions can do anything!
main.py
โ— Output
Click โ–ถ Run to see the output!

๐Ÿงฉ Why Use Functions?

โŒ Without functions

You write the same code over and over. It gets messy and hard to fix.

โœ… With functions

You write it once and call it whenever you need it. Clean and easy to fix!

๐Ÿ
Try this: create a function called 'print_joke' that prints your favorite joke. Then call it 3 times!
๐Ÿง 

Quick Quiz!

+10 XP

Which keyword do you use to create a function in Python?

๐Ÿ
Finished the lesson? Click the button to mark it complete and earn XP!