π Day 5/150 – Divide Two Numbers in Python
Welcome back to the 150 Python Programs: From Beginner to Advanced series.
Today we will learn how to divide two numbers in Python using different methods.
Division is one of the most basic and essential operations in programming.
π§ Problem Statement
π Write a Python program to divide two numbers.
1️⃣ Basic Division (Direct Method)
The simplest way is to directly use the division operator /.
Output:2.0
✔ Easy and straightforward
✔ Best for quick calculations
2️⃣ Taking User Input
We can make the program interactive by taking input from the user.
a = float(input("Enter first number: ")) b = float(input("Enter second number: "))print("Division:", a / b)✔ Works with decimal numbers
✔ More practical for real-world use
⚠️ Always ensure the second number is not zero to avoid errors.
3️⃣ Using a Function
Functions help organize and reuse code.
def divide(x, y): return x / y print(divide(10, 5))
✔ Clean and reusable
✔ Better for large programs
4️⃣ Using Lambda Function (One-Line Function)
A lambda function provides a short way to write functions.
divide = lambda x, y: x / y print(divide(10, 5))
✔ Compact code
✔ Useful for quick operations
5️⃣ Using Operator Module
Python provides a built-in operator module for arithmetic operations.
import operator print(operator.truediv(10, 5))
✔ Useful in advanced programming
✔ Cleaner when working with functional programming
π― Key Takeaways
Today you learned:
- Division using / operator
- Taking user input
- Using functions and lambda
- Using Python’s operator module
- Handling division by zero
.png)

0 Comments:
Post a Comment