Loading...
Loading...
Pass data into functions with parameters
Functions are more useful when they can take input. Parameters are variables that a function accepts — they let you pass different data each time you call the function.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
greet("Charlie") # Hello, Charlie!| Part | What it means |
|---|---|
| `name` | **Parameter** — a variable that receives the passed value |
| `"Alice"` | **Argument** — the actual value you pass when calling |
| `greet("Alice")` | Python assigns `name = "Alice"` inside the function |
def double(n):
result = n * 2
print(f"{n} doubled is {result}")
double(5) # n = 5 → "5 doubled is 10"
double(100) # n = 100 → "100 doubled is 200"
double(-3) # n = -3 → "-3 doubled is -6"Step by step for double(5):
def describe_pet(name, animal_type):
print(f"{name} is a {animal_type}!")
describe_pet("Max", "dog") # Max is a dog!
describe_pet("Whiskers", "cat") # Whiskers is a cat!| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `def greet():` then calling `greet("Alice")` | Function takes 0 arguments but got 1 — TypeError | Add a parameter: `def greet(name):` |
| `def greet(name):` then calling `greet()` | Missing required argument | Pass the argument: `greet("Alice")` |
| Wrong order of arguments | `describe_pet("cat", "Whiskers")` — swapped! | Match parameter order |
Define a function multiply(a, b) that prints "{a} times {b} is {a * b}". Call it with:
def multiply(a, b):
print(f"{a} times {b} is {a * b}")
multiply(3, 4)
multiply(7, 8)
multiply(10, 2)