









Python Functions with Parameters
In Python, functions allow you to group a block of code under a name and reuse it whenever needed. But functions become truly powerful when they can accept input in the form of parameters. These inputs allow functions to behave dynamically, depending on the data passed to them.
Why Parameters Matter
Without parameters, a function is just a repetitive block of code. With parameters, it becomes reusable, flexible, and adaptable. Think of parameters like ingredients in a recipe—you can create the same dish with different flavors, depending on what you add.
Defining a Function with Parameters
You define parameters inside the parentheses when writing a function. These are placeholders for values (called arguments) you'll pass when calling the function.
def greet(name):
print("Hello, " + name + "!")
Explanation: The function greet
takes one parameter called name
. When you call it, you must pass a value for name
.
Calling the Function with Arguments
def greet(name):
print("Hello, " + name + "!")
greet("Arjun")
greet("Bob")
Hello, Arjun!
Hello, Bob!
Note: The values "Arjun"
and "Bob"
are the actual arguments passed to the function. They replace the name
parameter temporarily when the function runs.
Multiple Parameters in a Function
You can define more than one parameter by separating them with commas.
def add(a, b):
result = a + b
print("The sum is:", result)
add(10, 5)
add(-3, 7)
The sum is: 15
The sum is: 4
Check: Ensure that you pass two values when calling this function. If you forget or pass the wrong number of arguments, Python will throw a TypeError
.
Parameters vs Arguments
- Parameter: The variable name in the function definition (like
name
,a
,b
). - Argument: The actual value passed when calling the function (like
"Arjun"
,10
).
Default Parameter Values
Sometimes, you want to make a parameter optional. You can do this by assigning it a default value.
def greet(name="User"):
print("Hello, " + name + "!")
greet("Arjun")
greet()
Hello, Arjun!
Hello, User!
Verification: Default values are used only when no argument is provided. You can override them by passing your own value.
Best Practices and Checks
- Always pass the correct number of arguments unless defaults are provided.
- Use descriptive names for parameters (avoid vague names like
x
,y
unless in math contexts). - Use
print()
orreturn
to observe and verify behavior.
Returning Value from Function
In many real-world scenarios, you may want the function to send back a value instead of printing it directly.
def multiply(x, y):
return x * y
result = multiply(4, 5)
print("Result:", result)
Result: 20
Why return? Returning a value gives you flexibility. You can store it, use it in calculations, or pass it to another function.