you can define functions using the def keyword. Here's a basic structure of a function:
def function_name(parameter1, parameter2, ...):
# Function body
# Code inside the function
# ...
# Optional: return statement
# Example
def greet(name):
print("Hello, " + name + "!")
# Calling the function
greet("Alice")
Explanation:
def: It is a keyword used to declare a function.function_name: Choose a descriptive name for your function.(parameter1, parameter2, ...): Define parameters that the function takes. Parameters are optional, and you can have none or multiple.:: Indicate the beginning of the function body.return: Use the return statement if you want your function to return a value. It's optional, and you can return multiple values if needed.Example with a return statement:
def add_numbers(a, b):
sum_result = a + b
return sum_result
# Calling the function and storing the result in a variable
result = add_numbers(3, 5)
print("Sum:", result)
In this example, the add_numbers function takes two parameters (a and b), calculates their sum, and returns the result. The returned value is then printed.