Parameters let you pass data into functions. Instead of hardcoding values, you make functions flexible to work with different inputs.
Copy
# Without parameters (inflexible)def greet_alice(): print("Hello, Alice!")# With parameters (flexible)def greet(name): print(f"Hello, {name}!")# Now it works for anyonegreet("Alice")greet("Bob")greet("Charlie")
Add parameters inside the parentheses when defining a function:
Copy
def introduce(name, age): print(f"My name is {name}") print(f"I am {age} years old")# Call with valuesintroduce("Alice", 25)introduce("Bob", 30)
The values you pass when calling a function are called “arguments”. The variables in the function definition are “parameters”. Many people use these terms interchangeably.
def greet(name, age): print(f"Hi {name}, you're {age}")# Wrong - too few argumentsgreet("Alice") # TypeError!# Wrong - too many argumentsgreet("Alice", 25, "NYC") # TypeError!# Rightgreet("Alice", 25)
Default values with mutable objects
Copy
# Wrong - don't use lists as defaultsdef add_item(item, list=[]): list.append(item) return list# Right - use None and create new listdef add_item(item, list=None): if list is None: list = [] list.append(item) return list