Table of Contents

Create a Four Function Calculator | Pictoblox

Example Description
Four functional calculator prompts the user to enter two values and an operator, performs the specified operation and displays the result.

Introduction:

This Python program allows users to perform basic arithmetic calculations using a four function calculator. It prompts the user to enter two values and an operator (+, -, *, or /), performs the specified operation, and displays the result. If the user inputs an invalid operator or attempts to divide by zero, an appropriate error message is displayed.

Code:

#Program to create a four function calculator
result = 0
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter any one of the operator (+,-,*,/): ")
if op == "+":
  result = val1 + val2
elif op == "-":
 if val1 > val2:
  result = val1 - val2
 else:
  result = val2 - val1
elif op == "*":
  result = val1 * val2
elif op == "/":
 if val2 == 0:
  print("Error! Division by zero is not allowed. Program terminated")
 else:
  result = val1/val2
else:
  print("Wrong input,program terminated")
print("The result is ",result)

Logic:

  1. Initialize the variables result, val1, and val2 to 0.
  2. Prompt the user to enter the first value and store it in the variable val1.
  3. Then Prompt the user to enter the second value and store it in the variable val2.
  4. Also Prompt the user to enter an operator and store it in the variable op.
  5. Use an if-elif-else structure to determine the operation to perform based on the operator:
    1. If the operator is “+”, add the values val1 and val2 together and assign the result to the variable result.
    2. If the operator is “-“, subtract the smaller value from the larger value and assign the result to the variable result.
    3. If the operator is “*”, multiply the values val1 and val2 together and assign the result to the variable result.
    4. If the operator is “/”, check if val2 is not zero. If it is zero, display an error message stating that division by zero is not allowed. Otherwise, divide val1 by val2 and assign the result to the variable result.
    5.  If the operator is not one of the valid options, display an error message stating that the input was wrong and terminate the program.
  6. Display the result to the user.

Output:

Enter value 1: val1
Enter value 2: val2
Enter any one of the operator (+,-,*,/):
>> The result is result