In Python, you can define default values for function parameters. This means that if a value is not provided for a parameter when the function is called, it will use the default value instead. Default values are specified using the = operator in the function definition.
Here's an example:
def greet(name, greeting="Hello"): print(greeting + ", " + name)greet("Alice") # Output: Hello, Alicegreet("Bob", "Hi") # Output: Hi, Bob |
greet is a function that takes two parameters: name and greeting. greeting has a default value of "Hello", which means that if it is not provided when the function is called, it will use the default value.When greet is called with only one argument, it uses the default value of "Hello" for the greeting parameter. When it is called with two arguments, it uses the provided value for the greeting parameter.
In addition to default values, you can also use flexible arguments in Python functions. There are two types of flexible arguments: *args and **kwargs.
*args is used to pass a variable number of arguments to a function. It allows you to pass any number of arguments to the function, and they will be collected into a tuple.
Here's an example:
def sum_numbers(*args): result = 0 for num in args: result += num return resultprint(sum_numbers(1, 2, 3, 4, 5)) # Output: 15 |
In this example, sum_numbers is a function that takes a variable number of arguments using *args. The function adds up all the numbers passed in and returns the result.
**kwargs is used to pass a variable number of keyword arguments to a function. It allows you to pass any number of keyword arguments to the function, and they will be collected into a dictionary.
Here's an example:
def print_person(**kwargs): for key, value in kwargs.items(): print(key + ": " + value)print_person(name="Alice", age="30", city="New York") # Output: name: Alice, age: 30, city: New York |
In this example, print_person is a function that takes a variable number of keyword arguments using **kwargs. The function prints out each keyword argument passed in as a key-value pair.
Using default and flexible arguments can make your functions more versatile and adaptable to different use cases.