๐ Day 13/150 – Simple Calculator in Python
Welcome back to the 150 Days of Python series! ๐ฅ
Today, we’ll build a Simple Calculator — one of the most important beginner projects.
This project helps you understand:
- Conditional statements
- Functions
- User input
- Error handling
๐ฏ Problem Statement
Create a Python program that performs basic operations:
- Addition ➕
- Subtraction ➖
- Multiplication ✖️
- Division ➗
✅ Method 1 – Using if-elif-else
print("Simple Calculator")
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == "+":
print("Result:", a + b)
elif operation == "-":
print("Result:", a - b)
elif operation == "*":
print("Result:", a * b)
elif operation == "/":
if b != 0:
print("Result:", a / b)
else:
print("Division by zero is not allowed")
else:
print("Invalid operation")
๐ Explanation:
input() → takes user input
float() → converts input into numbers
if-elif-else → checks which operation user selected
๐ Important:
Always check b != 0 before division to avoid errors.
✅ Method 2 – Using Functions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Division by zero not allowed"
print(add(10, 5))
print(subtract(10, 5))
print(multiply(10, 5))
print(divide(10, 5))
๐ Why use functions?
Code becomes modular
Easy to reuse
Cleaner structure
๐ This approach is closer to real-world coding.
✅ Method 3 – Using Lambda Functions
add = lambda x, y: x + y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y if y != 0 else "Cannot divide by zero"
print(add(10, 5))
print(subtract(10, 5))
print(multiply(10, 5))
print(divide(10, 5))
๐ Explanation:
lambda → creates small anonymous functions
Useful for short, one-line operations
๐ Best for concise code, but not always readable for beginners.
⚠️ Important Things to Remember
✔ Always convert input (int() or float())
✔ Handle division by zero
✔ Validate user input
✔ Keep code clean and readable
๐ง Summary
| Method | Concept |
|---|---|
| if-elif-else | Basic logic |
| Functions | Reusability |
| Lambda | Short & compact |
.png)

0 Comments:
Post a Comment