Skip to content

Functions Explained

Try This First: Before reading, try writing a function that adds two numbers: def add(a, b): return a + b. Then call it: print(add(3, 4)). What does it print?

Learn Your Way

Read Build Watch Test Review Visualize
You are here Projects Videos Quiz Flashcards Diagrams

A function is a reusable block of code with a name. You define it once, then call it whenever you need it.

Visualize It

See how Python enters a function, uses parameters, and returns a value: Open in Python Tutor

Defining a function

def greet(name):
    return f"Hello, {name}!"
  • def means "I am defining a function"
  • greet is the name you chose
  • name is a parameter — a value the function expects to receive
  • return sends a value back to whoever called the function

Calling a function

message = greet("Alice")
print(message)  # Hello, Alice!

# Or use it directly
print(greet("Alice"))  # Hello, Alice!

Functions without return

Some functions do something (like printing) but do not return a value:

def say_hello():
    print("Hello!")

say_hello()  # Prints: Hello!

If there is no return, the function returns None automatically.

Parameters and arguments

Parameters are the names in the function definition. Arguments are the values you pass when calling.

def add(a, b):     # a and b are parameters
    return a + b

add(3, 5)          # 3 and 5 are arguments

Default values

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Alice")           # Hello, Alice!
greet("Alice", "Hey")    # Hey, Alice!

Why functions matter

  1. Reuse — write code once, use it everywhere
  2. Organize — break big problems into named pieces
  3. Test — test each piece independently
  4. Readcalculate_tax(price) is clearer than 5 lines of math

Common mistakes

Forgetting parentheses when calling:

greet          # This is the function OBJECT, not a call
greet("Alice") # This CALLS the function

Forgetting to return:

def add(a, b):
    result = a + b
    # Forgot to return result!

total = add(3, 5)  # total is None, not 8

Defining after calling:

greet("Alice")    # Error! greet is not defined yet

def greet(name):
    return f"Hello, {name}!"

Practice

Quick check: Take the quiz

Review: Flashcard decks Practice reps: Coding challenges


← Prev Home Next →