Stuart's code Stuart's code is very nicely written, and provides much to a learner, but it didn't work for me. Fixed versions are too long for just a comment, so here they are.
Stuart's code is very nicely written, and provides much to a learner, but it didn't work for me. Fixed versions are too long for just a comment, so here they are.
Stuart's code is very nicely written, and provides much to a learner, but it didn't work for me. Fixed versions are too long for just a comment, so here they are.
Stuart's code is very nicely written, and provides much to a learner, but it didn't work for me. Fixed versions are too long for just a comment, so here they are.
Python 2
The exact version I use: 2.7.3
import operator
OPTIONS = {
'divide': operator.div,
'multiply': operator.mul,
'add': operator.add,
'subtract': operator.sub
}
def user_input():
while True:
try:
return input("Number: ")
except ValueError:
print("NOPE...")
def get_operation():
while True:
operation = raw_input("Multiply/Divide/Add/Subtract: ").lower()
try:
return OPTIONS[operation]
except KeyError:
print("Not an option.")
def play_again():
while True:
again = raw_input("Again? Yes/No: ").lower()
if again == "yes":
return True
elif again == "no":
return False
else:
print("Nope..")
while True:
operation = get_operation()
x = user_input()
y = user_input()
print operation(x, y)
if not play_again():
break
In Python 2, input
returns an integer, so int(input(...))
is redundant, and inputting string (for operation and going again) fails. The later is fixed by using raw_input
.
Python 3
The exact version I use: 3.2.3
import operator
OPTIONS = {
'divide': operator.truediv,
'multiply': operator.mul,
'add': operator.add,
'subtract': operator.sub
}
def user_input():
while True:
try:
return int(input("Number: "))
except ValueError:
print("NOPE...")
def get_operation():
while True:
operation = input("Multiply/Divide/Add/Subtract: ").lower()
try:
return OPTIONS[operation]
except KeyError:
print("Not an option.")
def play_again():
while True:
again = input("Again? Yes/No: ").lower()
if again == "yes":
return True
elif again == "no":
return False
else:
print("Nope..")
while True:
operation = get_operation()
x = user_input()
y = user_input()
print(operation(x, y))
if not play_again():
break
The obvious error here was the last print
statement: it's a function in Python 3, so print operation(x, y)
had to be replaced with print(operation(x, y))
.
The less obvious one is operator.div
which doesn't exist in Python 3, but was instead replaced by operator.truediv
and operator.floordiv
. In the spirit of this program, I assumed that the former is what was intended.