FUNCTION
A function is a block of organized, reusable code that performs a specific task. Functions provide a way to break down large programs into smaller, manageable pieces. They also promote code reuse and make your code more modular and readable.
Defining a Function
In Python, you can define a function using the def
keyword, followed by the function name and a set of parentheses. The function's code block is indented.
def greet():
print("Hello, World!")
Calling a Function
To execute a function and run its code, you need to call it. You call a function by using its name followed by a set of parentheses.
greet() # Output: Hello, World!
Function Parameters
Functions can accept parameters (inputs) to perform different actions based on the provided values. Parameters are specified in the parentheses when defining the function.
def greet(name):
print("Hello, " + name + "!")
You can then call the function and provide a value for the parameter.
greet("Alice") # Output: Hello, Alice!
Return Statement
Functions can also return a value using the return
statement. The returned value can be assigned to a variable or used in other parts of the code.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8
Default Parameters
You can provide default values for parameters, allowing the function to be called with fewer arguments.
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Bob") # Output: Hello, Bob!
greet("Alice", "Hi") # Output: Hi, Alice!
Docstrings
It's a good practice to include a docstring, a string that describes the purpose and usage of the function, immediately after the function definition.
def add(a, b):
"""
This function adds two numbers.
"""
return a + b
Example: Function with Multiple Parameters and Return Statement:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
"""
area = length * width
return area
# Call the function
length = 5
width = 3
result = calculate_area(length, width)
# Output the result
print(f"The area of the rectangle is: {result}")