LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operators Coding Problems · Question 3

Simple calculator for + - * / // % ** in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Read lines like 12 * 7 and print the result. Report division by zero and unknown operators instead of crashing.

Solution
main.py Run
import sys

for line in sys.stdin.read().splitlines():
    left, op, right = line.split()
    a, b = float(left), float(right)
    if op in ("/", "//", "%") and b == 0:
        result = "cannot divide by zero"
    elif op == "+":
        result = a + b
    elif op == "-":
        result = a - b
    elif op == "*":
        result = a * b
    elif op == "/":
        result = a / b
    elif op == "//":
        result = a // b
    elif op == "%":
        result = a % b
    elif op == "**":
        result = a ** b
    else:
        result = f"unknown operator {op}"
    if isinstance(result, float) and result.is_integer():
        result = int(result)          # print 84 rather than 84.0
    print(line, "=", result)

Output Verified by running it on Python 3

12 * 7 = 84
17 / 4 = 4.25
17 // 4 = 4
-17 % 4 = 3
2 ** 10 = 1024
5 / 0 = cannot divide by zero
3 @ 4 = unknown operator @

The zero check comes first, so no ZeroDivisionError can occur. float.is_integer() lets whole results print without .0.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links