A function in Python is a named block of code that performs a specific task. Functions allow programmers to reuse code, organize programs, and avoid repetition.
Defining a function
Python functions are defined using the def keyword:
def greet(name):
return f"Hello, {name}!"
-
greetis the function name -
nameis a parameter -
The function returns a result
Call the function:
message = greet("Mohi")
print(message) # Output: Hello, Mohi!
Why functions are important
-
Reusability – Write once, use many times.
-
Organized code – Makes programs modular and readable.
-
Avoid repetition – No need to rewrite the same code multiple times.
-
Easier debugging – Errors in functions can be fixed in one place.
-
Supports parameters and return values – Enables flexible data processing.
Example
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
print(add(10, 20)) # Output: 30
-
Functions make your code cleaner, efficient, and easier to maintain.