You don't need to define all of those functions because the operator
module already did, and they happen to have the same names as yours.
You use __name__
. That's great. Since you won't be defining functions anymore (because of ^^), this file will be completely useless as a module. Therefore, I probably wouldn't bother with it. I might define a function to get input and then have a while True
:
def get_answer(num1, num2, op):
...
if __name__ == '__main__':
while True:
try:
number1 = float(input(...))
number2 = float(input(...))
except ValueError:
print("That is not a number!")
continue
operator = input(...)
answer = get_answer(number1, number2, operator)
if answer is None:
print("Invalid operator!")
else:
print(answer)
That's just a rough draft. I probably wouldn't do that, but it is a possibility.
Never have a bare except
unless you are writing your own interpreter. You should have expectations for what errors you might get. Let's say you mis-spelled number1
and said numberl
. There would be an error, so it would say That is not a number!
... no matter what you type. What is your expectation? Of course, it's that the user might type an invalid float. In that case, use except ValueError:
I would use a dictionary for the different operations, and I would use the more standard operator names. That is, ^
instead of pow
. I would also tell the user the options at the beginning instead of telling him each time. Here is the full program: