Ad space (banner)
🐍Python Lessons
Lesson 27 / 69

Default Arguments (initial parameter values)

This lesson covers how to write default arguments in Python, so you can set an initial value used whenever an argument is omitted. It's written for anyone searching "Python default arguments tutorial".

Writing = value after a function parameter sets a "default value" that's automatically used whenever the caller omits that argument. Think of it like an order form — leave a field blank, and you get the usual default set. This means the function doesn't need to check for omission internally every time, keeping the function simple and easy for callers to use.

The sample code defines a function, def greet(name="Guest"):, where calling greet("Alice") uses that value, while calling greet() with the argument omitted falls back to the default, "Guest".

A common beginner mistake, when setting defaults on multiple parameters, is forgetting that parameters without a default must come first. Writing def f(a, b="x", c): — a parameter without a default appearing after one that has one — is a syntax error. There's also a well-known pitfall where using a list or dict as a default value can lead to unexpected behavior, so be careful there too.

In real development, default arguments are commonly used when designing a function where only some settings need to be changeable, or one with optional features. It's an essential technique for designing an API that's pleasant to use.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)