๐ Project Overview
In this project, you will create a simple calculator that performs basic mathematical operations.
- Taking input from the user
- Converting input into numbers
- Using arithmetic operators
- Using if-elif-else
- Displaying results
โ๏ธ Calculator Operations
Step 1: Take Input
First, take two numbers from the user.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
Step 2: Choose an Operation
Ask the user which mathematical operation they want to perform.
operator = input("Enter operator (+, -, *, /): ")
Step 3: Perform Calculation
Use conditional statements to perform the selected operation.
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
else:
print("Invalid operator")
๐ Complete Python Code
Now combine all the steps into one program.
print("===== Python Calculator =====")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 != 0:
result = num1 / num2
else:
print("Cannot divide by zero")
result = None
else:
print("Invalid operator")
result = None
if result is not None:
print("Result =", result)
๐งฎ Try the Calculator
Enter two numbers and choose an operation.
๐ป Example Output
===== Python Calculator ===== Enter first number: 20 Enter second number: 5 Enter operator (+, -, *, /): * Result = 100.0
๐ง Mini Challenge
Try improving the calculator by adding these features:
- Add modulus (%) operation
- Add power (**) operation
- Allow the user to perform multiple calculations
- Add a menu system