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¶
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
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:
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.
Default values¶
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # Hello, Alice!
greet("Alice", "Hey") # Hey, Alice!
Why functions matter¶
- 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
Common mistakes¶
Forgetting parentheses when calling:
Forgetting to return:
Defining after calling:
Practice¶
- 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 → |
|---|---|---|