Setting default values for parameters #
You can create a function with default value(s) for its parameter(s) by simply assigning the default value(s) to the parameter(s) in the function definition.
Here's an example:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("John") # Output: Hello, John!
greet("Alice", "Hi") # Output: Hi, Alice!
In this example, the greet() function takes two parameters: name and message. The message parameter has a default value of "Hello". If the caller doesn't provide a value for message, the default value will be used.
In the first call to greet(), we only pass the name parameter, so the default value of "Hello" is used for the message parameter. In the second call, we provide both name and message parameters, so the provided value for the message is used.
def print_height(unit = "cm", height):
print(f"You are {height} {unit} tall.")
Exercise #
Create a function with default parameter
Tests #
- Create a function
print_height - Function
print_heightshould take 2 parameters:heightas a numberunitwith the default value"cm"
print_height(170)should print"You are 170 cm tall."print_height(6, "ft")should print"You are 6 ft tall."
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules