Simple Calculator
Build a four-operation Python calculator. Students compare operator text, perform float arithmetic, and handle zero divisors or unsupported operator choices.
1# Take inputs2num1 = float(input("Enter first number: "))3operator = input("Enter operator (+, -, *, /): ")4num2 = float(input("Enter second number: "))56# Calculate7if operator == '+':8 result = num1 + num29elif operator == '-':10 result = num1 - num211elif operator == '*':12 result = num1 * num213elif operator == '/':14 if num2 != 0:15 result = num1 / num216 else:17 result = "Error: Division by zero"18else:19 result = "Error: Invalid operator"2021print(f"Result: {result}")
Output
Enter first number: 10 Enter operator (+, -, *, /): + Enter second number: 5 Result: 15.0
In this one
- Select arithmetic by text
- Guard a zero denominator
- Print numeric or error results
How it works
- 1
Read both float operands and the operator string.
- 2
Run the matching arithmetic branch, guarding division.
- 3
Store an error for invalid operations and print result.
Edge cases
What happens for division by zero?
What happens for division by zero?
The program prints its Error: Division by zero message.
Does ** work as an operator choice?
Does ** work as an operator choice?
No. Only the four listed operators are supported.
What's going on
Both operands are floats, while operator remains text. The branch chain selects addition, subtraction, multiplication, or division.
Division has its own zero-denominator guard before arithmetic runs. Instead of raising an exception for zero, this example stores an error message in result. Unsupported operator text does the same. The final print therefore displays either a number or explanatory text.
What happens for division by zero? The program prints its Error: Division by zero message.
Does ** work as an operator choice? No. Only the four listed operators are supported.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why convert operands to float?
Pick an answer to check it.
Question 2
What happens for division by zero?
Pick an answer to check it.
Questions people ask
What happens for division by zero?
The program prints its Error: Division by zero message.
Does ** work as an operator choice?
No. Only the four listed operators are supported.
Why convert operands to float?
Input returns text and arithmetic needs numeric values.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum