| jupytext |
|
||||||
|---|---|---|---|---|---|---|---|
| kernelspec |
|
Let's code a simple python calculator! 🧮 (8:20)
Build a functional calculator that performs basic mathematical operations!
- Combine user input with conditional statements
- Create a menu-driven program
- Handle different mathematical operations
- Validate user input
- Build a complete, useful program
A calculator program:
- Asks the user what operation they want to perform
- Gets the numbers to calculate
- Performs the requested operation
- Displays the result
1. Display available operators → 2. Get operator choice → 3. Get numbers →
4. Check operator and calculate → 5. Display result
:tags: [skip-execution]
operator = input("Enter operator (+, -, *, /, %): ")
:tags: [skip-execution]
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
Note: We use float() to handle both whole numbers and decimals
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
# ... and so onelif operator == "/":
if number2 == 0:
print("Error: Cannot divide by zero!")
else:
print(f"{number1} / {number2} = {number1 / number2}")
Add these operators:
**for exponentiation (power)//for floor divisionsqrtfor square root
Make the calculator run in a loop until user chooses to exit:
while True:
# calculator code here
continue_calc = input("Another calculation? (yes/no): ")
if continue_calc.lower() != "yes":
breakStore the last result and allow using it in next calculation:
memory = 0
# Allow user to type "M" to use memory valueif operator == "+":
result = number1 + number2
print(f"\n{number1} + {number2} = {result}")
print(f"Result: {result:.2f}") # 2 decimal places
valid_operators = ['+', '-', '*', '/', '%']
if operator not in valid_operators:
print("Invalid operator!")
:tags: [skip-execution]
try:
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
except ValueError:
print("Error: Please enter valid numbers!")
import math
if operator == "sqrt":
result = math.sqrt(number1)
elif operator == "sin":
result = math.sin(math.radians(number1))
elif operator == "cos":
result = math.cos(math.radians(number1))
history = []
# After each calculation:
history.append(f"{number1} {operator} {number2} = {result}")
# Display history:
for calc in history:
print(calc)
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 6 / 2 |
3.0 |
% |
Modulus | 7 % 2 |
1 |
** |
Power | 2 ** 3 |
8 |
// |
Floor Division | 7 // 2 |
3 |
# Allow: 5 + 3 * 2 - 1
# Parse and calculate following order of operationsAdd conversions:
- Temperature (C to F, F to C)
- Length (miles to km, km to miles)
- Weight (lbs to kg, kg to lbs)
# Calculate:
# - What is X% of Y?
# - X is what % of Y?
# - Percentage increase/decreaseUse tkinter to create a calculator with buttons:
import tkinter as tk
# Create calculator with button interface:tags: [skip-execution]
def calculator():
print("=== Simple Calculator ===")
print("Operations: +, -, *, /, %, **, //")
operator = input("\nEnter operator: ")
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Error: Division by zero!")
return
result = num1 / num2
elif operator == "%":
result = num1 % num2
elif operator == "**":
result = num1 ** num2
elif operator == "//":
result = num1 // num2
else:
print("Invalid operator!")
return
print(f"\n{num1} {operator} {num2} = {result}")
print(f"Result: {result:.2f}")
except ValueError:
print("Error: Please enter valid numbers!")
# Run calculator
calculator()
Continue to Chapter 9: Weight Converter to build another practical conversion program!