
You can practice this example using the Python Online Compiler:
When writing Python programs, you may sometimes need to perform the same task multiple times. Writing the same code again and again makes your program longer and harder to maintain.
Python functions help us solve this problem by allowing us to write code once and reuse it whenever needed.
Without Function
Consider this restaurant example:
item = "Biryani"
price = 300
print("Welcome to Ali's Restaurant")
print("Your order is:", item)
print("Price: Rs.", price)
print("----------------")
item = "Burger"
price = 450
print("Welcome to Ali's Restaurant")
print("Your order is:", item)
print("Price: Rs.", price)
print("----------------")
item = "Pizza"
price = 900
print("Welcome to Ali's Restaurant")
print("Your order is:", item)
print("Price: Rs.", price)
print("----------------")
Here, the same print() code is repeated for every order. If we have many orders, the code will become unnecessarily long.
With Function
We can put the repeated code inside a function and reuse it:
def order_food(item, price):
print("Welcome to Ali's Restaurant")
print("Your order is:", item)
print("Price: Rs.", price)
print("----------------")
order_food("Biryani", 300)
order_food("Burger", 450)
order_food("Pizza", 900)
The function order_food() contains the code for displaying an order. We simply call the function with different values.
For example:
order_food("Pizza", 900)
Here, "Pizza" and 900 are passed to the function as arguments.
Why Use Functions?
Functions make your Python code:
- Reusable – Write code once and use it multiple times.
- Shorter – Avoid unnecessary repetition.
- Easier to read – Keep related code organized.
- Easier to maintain – Make changes in one place instead of many.
Conclusion
Without functions, repeated code can make a program long and difficult to manage. With functions, we can write a task once and reuse it whenever needed.
Simple rule to remember:
Write once, use many times — that’s the basic idea of a function in Python.