๐Ÿ 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.