🐍 Default Arguments in Python
Understanding Default Values in Function Parameters
1. What is a Default Argument?
If the caller does not provide a value for that parameter, Python automatically uses the default value.
2. Syntax
def function_name(parameter=default_value):
statements
The parameter is assigned a value using the = operator.
3. Simple Example
def greet(name="Student"):
print("Hello", name)
greet()
greet("Bijan")
Output
In the first function call, no argument is supplied. Therefore, Python uses "Student".
In the second call, "Bijan" is supplied, so the default value is replaced.
4. How Default Arguments Work
5. Multiple Default Arguments
def student(name, course="BCA", year=1):
print("Name:", name)
print("Course:", course)
print("Year:", year)
student("Rahul")
Output
Here, course and year have default values.
6. Overriding a Default Argument
def student(name, course="BCA", year=1):
print(name, course, year)
student("Rahul")
student("Anita", "BSc", 2)
Output
When values are provided during the function call, they replace the default values.
7. Default Argument with Return
def power(number, exponent=2):
return number ** exponent
print(power(5))
print(power(5, 3))
Output
The default exponent is 2.
Therefore, power(5) calculates 5².
When 3 is supplied, the calculation becomes 5³.
8. Important Rule
Correct:
def student(name, age=18):
print(name, age)
Incorrect:
def student(age=18, name):
print(name, age)
The second form produces a
SyntaxError.
9. Parameter vs Default Argument
| Concept | Example | Meaning |
|---|---|---|
| Parameter | name | Variable that receives a value. |
| Default Parameter | name="Student" | Parameter with a predefined value. |
| Argument | "Bijan" | Actual value passed during the function call. |
10. Advantages of Default Arguments
The same function can work with or without optional values.
The caller does not need to provide every argument.
Default values can be replaced whenever necessary.
Functions become easier to use and understand.
11. Interactive Demonstration
Click the buttons to understand how default arguments work.
12. Important Points for Examination
- A default argument has a predefined value.
- Default values are specified while defining the function.
- If an argument is omitted, the default value is used.
- A supplied argument overrides the default value.
- Non-default parameters should come before default parameters.
- Default arguments are useful for optional parameters.
13. Quick Summary
def function_name(parameter=default_value):
statements
function_name()
function_name(value)
No argument → Default value is used
Argument supplied → Supplied value is used
No comments:
Post a Comment