0

I just wrote a simple calculator script in python, generally python should recognize the (-)minus,(*)multiplication,(/)divide sign by default but while considering this script it's fails to identify the signs. please leave your comments to clear me...

#! /usr/bin/python

print("1: ADDITION")
print("2: SUBTRACTION")
print("3: MULTIPLICATION")
print("4: DIVISION")

CHOICE = raw_input("Enter the Numbers:")

if CHOICE == "1":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a + b
    print c

elif CHOICE == "2":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a - b
    print c

elif CHOICE == "3":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a * b
    print c

elif CHOICE == "4":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a / b
    print c

else: 
 print "Invalid Number"
 print "\n"
Keanu
  • 53
  • 9
Prabhu Are
  • 463
  • 2
  • 7
  • 15

3 Answers3

5

You need to change your inputs, strings to integer or float. Since, there is division you are better change it to float.

a=int(raw_input("Enter the value of a:"))
a=float(raw_input("Enter the value of a:"))
billwild
  • 173
  • 1
  • 3
  • 12
4

When you get the input it is a string. The + operator is defined for strings, which is why it works but the others don't. I suggest using a helper function to safely get an integer (if you are doing integer arithmetic).

def get_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError, e:
            print "Invalid input"

a = get_int("Enter the value of a: ")
Tim
  • 11,710
  • 4
  • 42
  • 43
1

Billwild said u should change to make your variables integers. But why not float. It is not important if it is integer or float it must be number type. Raw_input takes any input like string.

a=float(raw_input('Enter the value of a: '))

Or for Tim's aproach

def get_float(prompt):
    while True:
        try:
            return float(raw_input(prompt))
        except ValueError, e:
            print "Invalid input"

a = get_float("Enter the value of a: ")

You can always convert result to float or to int or back. It is just matter what kind of calculator u are programming.

Domagoj
  • 1,674
  • 2
  • 16
  • 27