10. Functions in Python: Creating Reusable Code
Functions are one of the most important concepts in programming. They allow you to group code into reusable blocks, reduce repetition, and make your programs cleaner and easier to maintain.
1) Why Use Functions?
Without functions, you would repeat the same code many times. Functions help you:
- Avoid repetition (DRY principle)
- Organize large programs
- Improve readability
- Make debugging easier
2) Creating a Simple Function
In Python, you define a function using the def keyword.
def greet():
print("Hello, welcome to Python!")
greet()
The function runs only when it is called.
3) Functions with Parameters
Parameters allow you to pass data into a function.
def greet(name):
print("Hello,", name)
greet("Ali")
greet("Sara")
4) Returning Values
Functions can return values using the return keyword.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Once a function reaches return, it stops executing.
5) Default Parameters
You can assign default values to parameters.
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Omar")
6) Multiple Return Values
Python allows returning multiple values.
def calculate(a, b):
return a + b, a - b
sum_result, diff_result = calculate(10, 5)
print(sum_result, diff_result)
7) Variable Scope
Scope determines where a variable can be accessed.
x = 10 # Global variable
def show():
y = 5 # Local variable
print(x)
print(y)
show()
8) Keyword Arguments
def student(name, age):
print(name, "is", age, "years old")
student(age=22, name="Lina")
9) Lambda Functions (Short Functions)
Lambda functions are small anonymous functions.
square = lambda x: x * x
print(square(5))
10) Best Practices
- Keep functions small and focused
- Use clear function names
- Return values instead of printing inside functions (when possible)
- Avoid too many parameters
Conclusion
Functions are the foundation of structured programming in Python. They help you write reusable, maintainable, and clean code. Mastering functions prepares you for building larger applications, working with modules, and developing real-world software.