Parameters and Arguments in Python
Parameters and arguments are related to passing values into functions.
Parameters: Variables defined inside the function definition.
Arguments: Actual values passed when calling the function.
Example:
def greet(name):
print("Hello", name)
greet("Maha")
Output:
Hello Maha
Here:
-
nameis a parameter. -
"Mahalakshmi"is an argument.
Types of Arguments in Python
Python supports different ways of passing arguments to functions.
1. Positional Arguments
Values are passed according to the position of parameters.
Example:
def student(name, age):
print(name)
print(age)
student("John", 22)
Output:
John
22
Example:
def student(name, age, course):
print(name, age, course)
student(22, "John", "Python")
Output:
22 John Python
Here, Python does not automatically identify the data type or meaning of each argument. It assigns values according to their position.
2. Keyword Arguments
Values are passed using parameter names. The order of arguments does not matter.
Example:
def student(name, age):
print(name)
print(age)
student(age=22, name="John")
Output:
John
22
3. Default Arguments
A default value is assigned to a parameter in the function definition. If no argument is passed for that parameter, the default value is used.
Example:
def greet(name="Guest"):
print("Hello", name)
greet()
greet("John")
Output:
Hello Guest
Hello John
Incorrect Example:
def student(age=22, name):
print(name, age)
student("John"
This produces a SyntaxError because a non-default parameter (name) cannot follow a default parameter (age).
4. Variable-Length Arguments
Variable-length arguments allow a function to accept any number of arguments.
*a) args
The *args syntax allows a function to accept multiple positional arguments. The arguments are collected into a tuple.
Example:
def add(*numbers):
print(sum(numbers))
add(10, 20, 30)
Output:
60
**b) kwargs
The **kwargs syntax allows a function to accept multiple keyword arguments. They are collected into a dictionary.
Example:
def student(**details):
print(details)
student(name="John", age=22, course="Python")
Output:
{'name': 'John', 'age': 22, 'course': 'Python'}
Top comments (0)