My calculator won't do anything but adding

Issue

I have made a simple 4 function calculator app as practice

import time
import os
import subprocess
import sys

print("This is a calculator")
time.sleep(1)

num1 = float(input("Write a number of your choice: "))
op = input("Choose an operator: + - * / (or you can write their names)")
num2 = float(input("Write another number of your choice: "))
result = None


def cal(num1, op, num2, result):
    if op == "+" or "add" or "plus":
        result = num1 + num2
        return result
    elif op == "*" or "multiply" or "star" or "x":
        result = num1 * num2
        return result
    elif op == "/" or "divide" or "slash":
        result = num1 / num2
        return result
    elif op == "-" or "subtract" or "minus":
        result = num1 - num2
        return result
    else:
        print("Wrong input")
        subprocess.call(
            [sys.executable, os.path.realpath(__file__)] + sys.argv[1:])


print(cal(num1, op, num2, result))

I have encountered a problem, the calculator won’t do any operation but adding as seen in the following example

This is a calculator
Write a number of your choice: 9
Choose an operator: + - * / (or you can write their names)/
Write another number of your choice: 7
16.0

Solution

You can try this. It will work.
The syntax you entered is wrong.
You can also specify as op is "+" or op is "add". Something like this.

import time
import os
import subprocess
import sys

print("This is a calculator")
time.sleep(1)

num1 = float(input("Write a number of your choice: "))
op = input("Choose an operator: + - * / (or you can write their names)")
num2 = float(input("Write another number of your choice: "))
result = None


def cal(num1, op, num2, result):
    if op in ("+", "add", "plus"):
        result = num1 + num2
        return result
    elif op in ("*", "multiply", "star", "x"):
        result = num1 * num2
        return result
    elif op in ("/", "divide", "slash"):
        result = num1 / num2
        return result
    elif op in ("-", "subtract", "minus"):
        result = num1 - num2
        return result
    else:
        print("Wrong input")
        subprocess.call(
            [sys.executable, os.path.realpath(__file__)] + sys.argv[1:])


print(cal(num1, op, num2, result))

Answered By – Darshan Prajapati

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published