Function parameters allow you to pass information to a function when it is defined. They make functions more flexible because the same function can work with different values.
What are Parameters?
A parameter is a variable listed inside the parentheses of a function definition. It receives a value when the function is called.
For example:
def greet(name):
print("Hello", name)
greet("Abhishek")Output:
Hello AbhishekHere, name is a parameter, while "Abhishek" is the value passed to it.
Parameters can be used inside the function like normal variables.
def square(number):
print(number * number)
square(5)Output:
25Required Parameters
A required parameter is a parameter that must receive a value when the function is called. If you do not provide the required value, Python raises a TypeError.
def student(name):
print("Student:", name)
student("Rahul")Output:
Student: RahulIf the function is called without the required parameter:
student()Python raises an error:
TypeError: student() missing 1 required positional argument: 'name'Required parameters are useful when a function needs certain information to perform its task.
Multiple Parameters
A function can have more than one parameter. Each parameter is separated by a comma.
def add(a, b):
print(a + b)
add(10, 20)Output:
30A function can also have several parameters:
def student_info(name, age, course):
print("Name:", name)
print("Age:", age)
print("Course:", course)
student_info("Abhishek", 22, "Python")Output:
Name: Abhishek
Age: 22
Course: PythonWhen using positional values, the values are assigned to parameters according to their order.
def display(name, age):
print(name, age)
display("Amit", 25)Here, "Amit" is assigned to name, and 25 is assigned to age.
Parameters vs Arguments
Parameters and arguments are related, but they are used at different points.
- Parameter: A variable defined in the function definition.
- Argument: The actual value passed to the function when it is called.
def greet(name): # name is a parameter
print("Hello", name)
greet("Abhishek") # "Abhishek" is an argumentIn this example:
name → Parameter
"Abhishek" → Argument
Another example with multiple parameters:
def multiply(a, b):
print(a * b)
multiply(5, 4)Here, a and b are parameters, while 5 and 4 are arguments.
Understanding the difference is important when working with Python functions, especially when using different ways of passing values to functions.