Functions in Python are reusable blocks of code that perform a specific task. They allow you to break down your program into smaller, more manageable pieces.
Functions are defined using the def keyword, followed by the function name and parameters in parentheses.
def function_name(parameter1, parameter2):
# code block
return resultFunctions are called by using their name followed by parentheses and passing arguments if required.
result = function_name(argument1, argument2)
Parameters are the variables listed inside the parentheses in the function definition, while arguments are the values passed into the function when it is called.
def greet(name):
print("Hello, " + name)
greet("Alice")Here's an example of a function that adds two numbers:
def add(a, b):
return a + b
result = add(3, 5)
print("The sum is:", result)