Functions in Python
Functions in Python are used to group a set of statements that perform a specific task.
Instead of writing the same code again and again, we write it once inside a function and reuse it whenever needed.
1. Simple Function
A function is created using the keyword def. Once defined,
it can be called multiple times.
Example
def greet():
print("Hello, welcome to Python")
greet()
Explanation
def greet():defines a function namedgreet.- The code inside the function runs only when it is called.
greet()calls the function.- The message is printed when the function executes.
2. Function with Parameters
Functions can accept parameters, which allow us to pass data into a function.
Example
def greet(name):
print("Hello", name)
greet("Alice")
greet("Bob")
Explanation
nameis a parameter.- Values like
"Alice"and"Bob"are passed during function calls. - The function uses the passed value to print a personalized message.
- The same function works with different inputs.
3. Function with Return Value
Functions can return a value using the return keyword.
Example
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Explanation
aandbare parameters.return a + bsends the result back to the caller.- The returned value is stored in
result. print(result)displays the output.
4. Function with Default Parameter
A function can have a default value for a parameter.
Example
def greet(name="User"):
print("Hello", name)
greet()
greet("Rahul")
Explanation
"User"is the default value.- If no argument is passed, the default value is used.
- If an argument is passed, it replaces the default value.
5. Function with Multiple Parameters
A function can take more than one parameter.
Example
def calculate_area(length, width):
print("Area =", length * width)
calculate_area(5, 4)
Explanation
lengthandwidthreceive values from the function call.- The function multiplies the values.
- The result is printed as the area.
Final Note
Functions make programs organized, reusable, and easy to understand.
Learning functions is essential for writing clean and professional Python code.