Project Introduction
In this project, we will build a simple calculator that can perform basic mathematical operations.
The calculator will allow the user to enter two numbers and choose an operation such as:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
Taking User Input
Python's input() function allows us to receive information from the user.
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
print(number1)
print(number2)
The important thing to understand is that input() normally returns text.
Converting Input to Numbers
Because calculator operations require numbers, we can convert the input using int() or float().
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
print(number1 + number2)
Using float() also allows decimal values such as 10.5 or 25.75.
Understanding Operators
Our calculator needs arithmetic operators.
addition = 10 + 5 subtraction = 10 - 5 multiplication = 10 * 5 division = 10 / 5 print(addition) print(subtraction) print(multiplication) print(division)
Choosing an Operation
We can ask the user which operation they want to perform.
operation = input("Enter operation (+, -, *, /): ")
print(operation)
Using if / elif / else
Now we can check the selected operation.
if operation == "+":
print(number1 + number2)
elif operation == "-":
print(number1 - number2)
elif operation == "*":
print(number1 * number2)
elif operation == "/":
print(number1 / number2)
Handling Division by Zero
A calculator should not attempt to divide a number by zero.
elif operation == "/":
if number2 == 0:
print("Cannot divide by zero")
else:
print(number1 / number2)
Creating a Function
Functions allow us to organize reusable code.
def calculate(a, b, operation):
if operation == "+":
return a + b
elif operation == "-":
return a - b
elif operation == "*":
return a * b
elif operation == "/":
if b == 0:
return "Cannot divide by zero"
return a / b
return "Invalid operation"
Calling the Function
After creating the function, we can call it with our values.
result = calculate(
number1,
number2,
operation
)
print("Result:", result)
Complete Project Flow
What You Practiced
- Python variables
- input() function
- float() conversion
- Arithmetic operators
- if / elif / else
- Comparison operators
- Functions
- return statement
- Basic error handling
Ready to Run the Complete Project?
You have learned the important concepts. Now open the complete Python Calculator and test it with different numbers and operations.
Run Complete Project →