Functions: Reusable Blocks of Code

What is a function?

A function is a named block of code that does one job. You write it once and call (use) it whenever you need it. You've already used built-in functions like print(), len() and input(). Now you'll make your own.

Think of it like this: A function is like a recipe card. You write the recipe for tea once. Every time someone wants tea you don't re-invent it – you just follow the card.

Defining a function

def say_hello():
    print("Hello!")
    print("Welcome to Python.")

say_hello()
say_hello()

Output

Hello!
Welcome to Python.
Hello!
Welcome to Python.
  • def means “define a function”.
  • say_hello is its name, followed by brackets and a colon.
  • The indented lines are the function's body – the code it runs.
  • Defining a function doesn't run it. say_hello() calls it.

Common mistake: Calling a function before it's defined. Python reads from top to bottom, so put the def first.

Why use functions?

  • No repeating yourself – write the code once, use it many times.
  • Easier to read – a good name like calculate_total() explains what happens.
  • Easier to fix – fix a bug in one place and it's fixed everywhere.
HOME LEARN COMMUNITY DASHBOARD