Reputation: 99
I'm having problems with the "operator" variable. So far I have only tried +. It doesn't seem to register and I can't figure out why. i'm using the online python interpreter on repl.it because I'm having problems with my computer.
EDIT: I should probably add that I just started learning Python (I had some Java experience but it was years ago). I'm trying to create a simple text calculator.
restart=raw_input("to restart calculations enter \'true\'")
#if restart == "true":
#stuff
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
answer=numone+numtwo
print(answer)
print("test")
if operator == "-":
answer=numone-numtwo
print(answer)
else:
print("something went wrong")
#if operator == "*":
Upvotes: 0
Views: 173
Reputation: 8702
Give elif
to the second statement
since user give '+'
first if
statment excutes but in next statement it fails
and go to the else
so for +
you get two result
both addition and something wrong
and also you need to convert the operands
to integer
one more thing while converting to integer you need check right conditions for integer else it will give error
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
try:
answer=int(numone)+int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
elif operator == "-":
try:
answer=int(numone)-int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
else:
print("something went wrong")
Upvotes: 2
Reputation: 95998
Your problem is that you're concatenating two strings, you should cast to int
before:
answer = int(numone) + int(numtwo)
Why? Because raw_input
reads the input as string.
Upvotes: 3