🐍 Lesson 10: Functions

Teach Python your own commands

← Back to Python Basics

🧰 What is a function?

A function is a reusable block of code with a name. You write it once, then call it whenever you need it — no copy-pasting. You've already used functions: print() and len() are built-in ones!

✍️ Defining your own

Use the def keyword. Don't forget the colon and indentation:

def greet(): print("Hello there!") print("Welcome to Python!") greet() # call it — runs the two prints greet() # call it again!

📌 Define, then call

Writing def greet(): only creates the function. Nothing happens until you call it with greet().

🎁 Parameters — giving input

A parameter lets you pass information into a function so it can behave differently each time:

def greet(name): print(f"Hello, {name}!") greet("Maya") # Hello, Maya! greet("Leo") # Hello, Leo!

You can have several parameters:

def add(a, b): print(a + b) add(3, 4) # 7

📤 return — sending a value back

Often you want a function to compute and hand back a result, instead of just printing. That's what return does:

def add(a, b): return a + b total = add(3, 4) # total is now 7 print(total) # 7 print(add(10, 5)) # 15

print vs return

print just shows a value on screen. return gives it back so you can store it in a variable and use it later. They're different!

🌟 Why functions are awesome

  • Reuse — write once, use everywhere.
  • Organized — break a big problem into small named pieces.
  • Easy to fix — change it in one place, fixed everywhere.

✅ What you learned

  • Define a function with def name(): and a colon + indentation.
  • Call it with name() to run it.
  • Parameters pass information in.
  • return sends a result back to be used.