I'm trying to make this printing calculator program in Python 2.7.8, but whenever I run it, it outputs this:
0
0
0
0
And so on. It does this infinitely and never stops. I would really appreciate any help. Here is my code. Thanks!
import msvcrt # Windows only!
def getch():
return msvcrt.getch()
def putch(ch):
msvcrt.putch(ch)
total = 0
pendingOp = 0
print "*** Calculator ***"
while True:
ch = getch()
if ch == "q": break # quit
if ch == "c": # clear the display
total = 0
pendingOp = 0
elif ch == "a" or "s" or "m" or "d": # add, subtract, multiply, divide
pendingOp = ch
elif (ch >= "0" and ch <= "9"):
newNumber = int(ch)
if pendingOp == 0:
total = newNumber
else:
if pendingOp == "a": total = total + newNumber
elif pendingOp == "s": total = total - newNumber
elif pendingOp == "m": total = total * newNumber
elif pendingOp == "d": total = total / newNumber
pendingOp = 0
print total
Welcome to the wonderful world of converting between different string encodings. That particular API returns a byte string which is different from Python's normal string UTF encoding, and the two won't compare. Try for example
if ch == b'q'
.Another solution is to get the wide characters directly:
Of some question to me is that Ctrl-C is returned (on Windows, obviously), even though the API documentation for my python says it shouldn't be.
Update:
abarnert's answer seems to be the root cause. I'm leaving this answer because string encoding issues causes the same symptoms on Python 3 running in the console, and in general are a cause of similarly interesting headaches.