Course contentsShow
← Python
Lesson 141 of 1,0603. Functions and ModularizationFree lesson

Configuring Default Parameter Values

You will learn to assign default values to parameters, allowing functions to be called with fewer arguments when standard inputs suffice.

Configuring Default Parameter Values

In this lesson, you will learn how to make your functions more flexible by assigning default values to parameters, allowing you to call them without providing every argument every time.

Why use default values?

Sometimes, a function is used in a specific way 90% of the time. Instead of forcing yourself to type the same input over and over, you can tell Python: "If I don't provide a value for this parameter, use this specific default instead."

For example, imagine you are writing a function to greet a user. Most of the time, you want the greeting to be "Hello," but sometimes you might want to use a different word like "Welcome."

Defining the default

You assign a default value by using the = operator inside the function definition parentheses. Take a look at this example:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

# Call using both arguments
greet("Alice", "Welcome")  # Output: Welcome, Alice!

# Call using only the required argument
greet("Bob")               # Output: Hello, Bob!

In the second call (greet("Bob")), we didn't provide a second argument. Python sees that greeting is missing and automatically assigns it the value "Hello" that we defined in the function header.

A few rules to remember

  • Order matters: Parameters with default values must always come after parameters without default values. If you try to put a default parameter before a regular one, Python will raise a SyntaxError because it won't know which value belongs to which parameter.
  • Flexibility: When you call the function, you can provide as many arguments as you like, starting from the left. Providing an argument will always override the default value you set.

By using default parameters, you reduce repetitive code and make your functions easier to read and maintain for common scenarios.

Key Takeaway: Default parameter values allow you to define a "standard" behavior for your functions while still keeping the flexibility to override those settings when needed.