0

I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:

print ("Enter your first number")
num1 = input()
print("Enter your second number") 
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")

3 Answers3

0

I think you want to be using == instead of is to compare string literals with a variable. I'd expect your usage to always return false.

Juan Tomas
  • 4,905
  • 3
  • 14
  • 19
0

@Fjoni Yzeiri: Hi folk,

This is a common issue when starting with Python, as you don't declare the variable type of the input, it will save it as a String, so if you concatenate (+ in Python) it will concatenate the two Inputs.

To solve this you have to explicitly cast this values into Integers, it means:

print ("Enter your first number")
num1 = int(input()) # Cast to int here
print("Enter your second number") 
num2 = int(input()) # Cast to int here
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")

Of course, this is a very simple use case, if you want to learn a bit more, try to caught the exception when it tries to cast a non-integer string. It will teach you nice stuff ;)

Rafael Aguilar
  • 3,084
  • 1
  • 25
  • 31
  • Thanks. I was writing the answer somone gave me while you wrote your answer at the same time xD –  Jul 21 '16 at 16:17
0

The problem is solved now. Someone posted the answer but he deleted it I think and I couldn't upvote it. I needed to change

num1 = input()

to

num1 = int(input())