π Day 92/150 – Function with Default Arguments in Python
Default arguments allow you to assign a default value to a function parameter. If the caller doesn't provide a value for that parameter, Python automatically uses the default value. This makes functions more flexible and easier to use.
In this post, we'll explore four different ways to use default arguments in Python.
Method 1 – Basic Default Argument
Assign a default value to a function parameter.
def greet(name="Guest"): print("Hello,", name) greet() greet("Alice")
Output
Hello, Guest
Hello, Alice
Explanation
- The parameter name has a default value of "Guest".
- Calling greet() uses the default value.
- Calling greet("Alice") replaces the default value with "Alice".
Method 2 – Multiple Default Arguments
A function can have more than one default argument.
def student(name="Unknown", age=18): print("Name:", name) print("Age:", age) student() student("John", 20)
Output
Name: UnknownAge: 18Name: John
Age: 20
Explanation
- Both parameters have default values.
- If no arguments are provided, the defaults are used.
- Passing values overrides the defaults.
Method 3 – Mix of Required and Default Arguments
A function can have both required and default parameters.
def power(number, exponent=2): print(number ** exponent) power(5) power(5, 3)
Output
25 125
Explanation
- number is required.
- exponent has a default value of 2.
- power(5) calculates 5².
- power(5, 3) calculates 5³.
Method 4 – Taking User Input
Use user input with a function that has a default argument.
def welcome(name="Guest"): print("Welcome,", name) name = input("Enter your name (press Enter to skip): ") if name: welcome(name) else: welcome()
Sample Input
SamOutput
Welcome, SamSample Input
Output
Welcome, Guest
Explanation
- If the user enters a name, it is passed to the function.
- If the user presses Enter without typing anything, the default value "Guest" is used.
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Default Argument | Simple functions |
| Multiple Default Arguments | Functions with several optional values |
| Required + Default Arguments | Flexible function design |
| User Input | Interactive programs |
π₯ Key Takeaways
- Default arguments provide values that are used when no argument is passed.
- They make functions more flexible and reduce the need to pass common values repeatedly.
- Required parameters must come before default parameters in a function definition.
- Default arguments can be overridden by passing your own values.
- They are commonly used to simplify function calls and improve code readability.


0 Comments:
Post a Comment