Functions with Default Values
Functions with default values, or default arguments, are a mechanism that allows a function to receive parameters with default values if an argument is not provided when calling it. This makes it easier to write more flexible and versatile functions.
Syntax
Section titled “Syntax”In the function definition, a value is assigned to each parameter that can have a default value.
When calling the function, the arguments corresponding to the parameters with default values can be omitted, and the function will use these values instead.
Implementation
Section titled “Implementation”In this section, we will explore how to construct functions in Python in a flexible and reusable way. We will see different ways to define and use parameters to adapt to different needs, such as default values or optional arguments.
Optional Parameter
Section titled “Optional Parameter”We can make a parameter optional, which helps to make the use of the function more flexible for different scenarios.
def greet(name, surname=None):if surname: print(f'Hello, {name} {surname}')else: print(f'Hello, {name}')
name = 'Py'surname = 'Docs'greet(name)greet(name, surname)
Output:
Hello, PyHello, PyDocs
Default Parameter
Section titled “Default Parameter”If the user does not provide the second argument (exponent), the function defaults to squaring (exponent = 2). This allows the function to be used more flexibly, without always having to write both arguments.
def power(base, exponent=2):print(f'{base} raised to {exponent} is {base ** exponent}')
power(5) # Uses the default value 2power(5, 3) # Uses the provided value
Output:
5 raised to 2 is 25 5 raised to 3 is 125
Benefits
Section titled “Benefits”-
Flexibility: Allows you to call the function in different ways, depending on the need.
-
Simplification: Avoids the need to pass unnecessary arguments in all cases.
-
Increased readability: Facilitates code comprehension by explicitly showing the default values.