Parameters and Default Values
You’ll learn how to define functions with parameters and give those parameters default values so that the function can still run even when no argument is provided.
Function Parameters Refresher
A parameter is a variable that a function accepts as input. When you call the function, you pass in an argument (the actual value).
def greet(name):
print("Hello", name)
greet("Kofi") # Output: Hello Kofi
Using Default Values
Sometimes you want a function to run even when no argument is passed. You can assign default values to parameters.
def greet(name="Stranger"):
print("Hello", name)
greet("Ama") # Output: Hello Ama
greet() # Output: Hello Stranger
This is useful when:
- You want to provide a fallback value.
- You want your function to be more flexible.
Real-World Example
Let’s say you're building a product info display. If no price is entered, it defaults to 0
.
Multiple Parameters with Defaults
You can mix parameters with and without defaults. Just remember: non-default parameters must come first!
def describe_pet(animal, name="Unknown"):
print(f"This is a {animal} named {name}.")
describe_pet("cat", "Whiskers")
describe_pet("dog")
Works fine
?describe_pet(name="Buddy", animal="dog")
also works, because we’re using keyword arguments.
Exercise: Try It Yourself!
- Create a function
welcome(name="Guest")
that printsWelcome, <name>!
. - Write a function
order_item(item="Bread", quantity=1)
that prints something like:You ordered 1 Bread(s)
. -
Build a function
say_goodbye(name="friend", language="English")
:- If language is English, print
Goodbye <name>!
- If language is French, print
Au revoir <name>!
- Test it with and without arguments.
- If language is English, print
Summary
- Parameters are values your function needs to work.
- You can assign default values to make functions flexible.
- Always place default parameters after the required ones.