0

When i run through my calculator, it gives the following results;

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 1
Enter second number: 5
Invalid! Input

Can anyone explain to me why it is responding with my else if statement, i'v checked the code many times, plus i have copied paste the code directly, as is, after much frustration, yet it yields the same result?

# A simple calculator that can add, subtract, multiply and divide.

# define functions
def add(x, y):
 """This function adds two numbers"""
 return x + y

def subtract(x, y):
 """This function subtracts two numbers"""
 return x - y

def multiply(x, y):
 """This function multiplies two numbers"""
 return x * y 

def divide(x, y):
 """This function divides two numbers"""
 return x / y 


# Take input from the user
print ("Select operation.")
print ("1.Add")
print ("2.Subtract")
print ("3.Multiply")
print ("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
    print(num,"+",num2,"=", add(num1,num2))

elif choice == '2':
    print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
    print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
    print(num1,"/",num2,"=", divide(num1,num2))

else:
    print("Invalid! Input")
musically_ut
  • 34,028
  • 8
  • 94
  • 106
Vine
  • 395
  • 3
  • 13
  • 1
    You are using Python 2, I bet. In Python 2, `input()` *evaluates* the input as a Python expression, so `choice` is an integer. Run your code with Python 3, or find yourself a Python 2 version to copy (e.g. using `raw_input()` instead). – Martijn Pieters Aug 22 '15 at 07:38
  • Possibly related: [How can I read inputs as integers in Python?](http://stackoverflow.com/a/20449433/1903116) – thefourtheye Aug 22 '15 at 07:44

1 Answers1

2

You're using Python 2, where input() evaluates what is entered; so when you enter 2, for instance, choice contains the int 2. Try entering '2' into your current code (including the quotes). It'll act as you expect entering 2 to act.

You should use raw_input() on Python 2 and input() on Python 3. If you want your code to be compatible with both, you can use the following code, after which you can always just use input():

try:
    input = raw_input  # Python 2
except NameError:  # We're on Python 3
    pass  # Do nothing

You can also use the six package, which does this and many other Python 2/3 compatibility things.

In Python 3 input() does what raw_input() does in Python 2, and Python 2's input() is gone.

Cyphase
  • 11,502
  • 2
  • 31
  • 32