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?
| 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.
See how Python enters a function, uses parameters, and returns a value: Open in Python Tutor
def greet(name):
return f"Hello, {name}!"defmeans "I am defining a function"greetis the name you chosenameis a parameter — a value the function expects to receivereturnsends a value back to whoever called the function
message = greet("Alice")
print(message) # Hello, Alice!
# Or use it directly
print(greet("Alice")) # Hello, Alice!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 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 argumentsdef greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # Hello, Alice!
greet("Alice", "Hey") # Hey, Alice!- Reuse — write code once, use it everywhere
- Organize — break big problems into named pieces
- Test — test each piece independently
- Read —
calculate_tax(price)is clearer than 5 lines of math
Forgetting parentheses when calling:
greet # This is the function OBJECT, not a call
greet("Alice") # This CALLS the functionForgetting to return:
def add(a, b):
result = a + b
# Forgot to return result!
total = add(3, 5) # total is None, not 8Defining after calling:
greet("Alice") # Error! greet is not defined yet
def greet(name):
return f"Hello, {name}!"- Level 00 / 13 Functions
- Level 0 / 02 Calculator Basics
- Level 0 / 03 Temperature Converter
- Level 0 / 12 Contact Card Builder
- Level 1 / 01 Input Validator Lab
- Level 1 / 02 Password Strength Checker
- Level 1 / 03 Unit Price Calculator
- Level 1 / 04 Log Line Parser
- Level 1 / 05 Csv First Reader
- Level 1 / 06 Simple Gradebook Engine
- Level 1 / 07 Date Difference Helper
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|