Skip to content
Programs · Program 6-3

Q.Program 6-3: Write a program to create a simple calculator performing only four basic operations.
The program should do the following:
• Accept two numbers from the user.
• Ask user to input any of the operator (+, -, *, /). An error message is displayed if the user enters anything else.
• Display only positive difference in case of the operator "-".
• Display a message “Please enter a value other than 0” if the user enters the second number as 0 and operator ‘/’ is entered.

Punjab PsebTextbookSubjective· 3mImportance★★★★★est
15% · 6/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A four-function calculator is an if–elif ladder on the operator character, with NESTED ifs handling the two special rules — positive difference for "-" and the divide-by-zero guard for "/".

The idea. The calculator has five outcomes (four operators plus "invalid"), which maps to an if–elif–else ladder on a string. Two requirements need a second, nested decision inside their branch: the "-" branch reuses Program 6-2's positive-difference logic, and the "/" branch must check the divisor BEFORE dividing — validating input rather than crashing with ZeroDivisionError.

Program

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter the operator (+, -, *, /): ")

if op == "+":
    print("Result:", num1 + num2)
elif op == "-":
    if num1 > num2:                      # display only the positive difference
        print("Result:", num1 - num2)
    else:
        print("Result:", num2 - num1)
elif op == "*":
    print("Result:", num1 * num2)
elif op == "/":
    if num2 == 0:                        # guard BEFORE dividing
        print("Please enter a value other than 0")
    else:
        print("Result:", num1 / num2)
else:
    print("Error: Please enter a valid operator (+, -, *, /)")

Sample runs (all four requirements exercised)

Enter first number: 10
Enter second number: 5
Enter the operator (+, -, *, /): +
Result: 15.0
Enter first number: 5
Enter second number: 20
Enter the operator (+, -, *, /): -
Result: 15.0
Enter first number: 10
Enter second number: 0
Enter the operator (+, -, *, /): /
Please enter a value other than 0
Enter first number: 10
Enter second number: 5
Enter the operator (+, -, *, /): %
Error: Please enter a valid operator (+, -, *, /)
``` …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.