Skip to content

Default argument in Python

  • by

In Python, a default argument is a feature that allows you to assign a default value to a function parameter. This default value is used when no argument is provided for that parameter during the function call.

The syntax for specifying a default argument is as follows:

def function_name(parameter1, parameter2=default_value):
    # Function body
  • function_name: This is the name of your function.
  • parameter1: This is a required parameter, meaning that the caller must provide a value for it.
  • parameter2: This is an optional parameter with a default value assigned to it. If the caller does not provide a value for parameter2, the default value will be used instead.
  • default_value: This is the value assigned to parameter2 if no argument is provided by the caller. It can be any valid Python expression or literal value.

By defining default arguments, you can make certain parameters of a function optional. If the caller provides a value for the corresponding argument, the provided value is used. However, if no argument is provided, the default value is used instead.

Default argument in Python example

Here’s an example that demonstrates the use of default arguments in Python:

def greet(name, greeting="Hello"):
    print(greeting, name)

# Calling the function with both arguments
greet("John", "Hi")  # Output: Hi John

# Calling the function with only the name argument
greet("Alice")  # Output: Hello Alice


Default argument in Python

Advance example

def calculate_total_bill(amount, tip_percentage=10):
    tip_amount = amount * tip_percentage / 100
    total_bill = amount + tip_amount
    return total_bill

# Calling the function with both arguments
bill_with_tip = calculate_total_bill(100, 15)
print("Total bill with 15% tip:", bill_with_tip) 

# Calling the function with only the amount argument
bill_with_default_tip = calculate_total_bill(100)
print("Total bill with default 10% tip:", bill_with_default_tip)

Default arguments provide flexibility by allowing the caller to omit certain arguments if they are not needed, using the default values specified in the function definition.

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *