Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Simple Calculator

Build a four-operation Python calculator. Students compare operator text, perform float arithmetic, and handle zero divisors or unsupported operator choices.

BeginnerPhase 6 - Category 5: Real-World Logic ProblemsExample 11 of 15
simple-calculator.py
1# Take inputs
2num1 = float(input("Enter first number: "))
3operator = input("Enter operator (+, -, *, /): ")
4num2 = float(input("Enter second number: "))
5
6# Calculate
7if operator == '+':
8 result = num1 + num2
9elif operator == '-':
10 result = num1 - num2
11elif operator == '*':
12 result = num1 * num2
13elif operator == '/':
14 if num2 != 0:
15 result = num1 / num2
16 else:
17 result = "Error: Division by zero"
18else:
19 result = "Error: Invalid operator"
20
21print(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. 1

    Read both float operands and the operator string.

  2. 2

    Run the matching arithmetic branch, guarding division.

  3. 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.