In Python, a function is a block of reusable code that performs a specific task.
Functions help
you organize your code, avoid repetition, and make it more modular and readable.
🔹 Defining a Function
You define a function using the def keyword:
def greet():
print("Hello, world!")
def – tells Python you're defining a function.
greet() – the name of the function.
The code inside the function runs when you call the function.
🔹 Calling a Function
To use (or call) a function:
greet()
🔹 Function with Parameters
You can pass information to functions using parameters:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
🔹 Function with Return Value
Functions can return a value using the return keyword:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
🔹 Why Use Functions?
Makes code reusable
Keeps code organized
Easier to debug and test
Improves readability
🔹 Example: Putting It All Together
def calculate_area(width, height):
area = width * height
return area
print(calculate_area(5, 10)) # Output: 50