Python Tutorial

Introduction to Python Default Parameters

In Python, when you define a function, you can specify a default value for each parameter. This allows you to provide default behavior while still retaining the flexibility to override these defaults if needed.

 

Specifying Default Values

To specify default values for parameters, you use the following syntax:

def function_name(param1, param2=value2, param3=value3, ...):

In this syntax, you assign default values (value2, value3, etc.) to parameters using the assignment operator (=). When you call a function and provide an argument for a parameter with a default value, the function will use that argument instead of the default value. If you don't provide an argument, the function will use the default value.

It is important to note that parameters with default values must come after parameters without default values. Placing default parameters before non-default ones will result in a syntax error:

def function_name(param1=value1, param2, param3):  # This causes a syntax error!

 

Python Default Parameters Example

The following example defines the greet() function, which returns a greeting message:

def greet(name, message='Hi'):
    return f"{message} {name}"

In this function, name is a required parameter, while message has a default value of 'Hi'.

Here’s how you can call the greet() function by passing both arguments:

greeting = greet('John', 'Hello')
print(greeting)

Output:

Hello John

Since the second argument is provided, the function uses this value instead of the default one.

Now, let’s call the greet() function without passing the second argument:

greeting = greet('John')
print(greeting)

Output:

Hi John

In this case, the function uses the default value for the message parameter.

 

Multiple Default Parameters

You can redefine the greet() function to have both parameters with default values:

def greet(name='there', message='Hi'):
    return f"{message} {name}"

With this definition, you can call the greet() function without any arguments:

greeting = greet()
print(greeting)

Output:

Hi there

If you want the function to return a greeting like "Hello there," you might try calling the function like this:

greeting = greet('Hello')
print(greeting)

However, this will return an unexpected result:

Hi Hello

Because the 'Hello' argument is used for the name parameter, not the message parameter. To achieve the desired output, use keyword arguments:

greeting = greet(message='Hello')
print(greeting)

Output:

Hello there

 

Summary

  • Use Python default parameters to simplify function calls and provide default behavior.
  • Place default parameters after non-default parameters to avoid syntax errors.

Understanding and using default parameters effectively can make your code more flexible and reduce the need for multiple function overloads. This approach helps in creating cleaner and more maintainable code.