For a beginner this is pretty good. But, there are three glaring problems with it.
- You should use a 'main' function.
- You should use a dictionary.
operators
Starting with (2), a dictionary holds a key value pair,. ifIf you've come across lists/arrays, it's like them, apart from that you can use a lot of different types, not just integers.
Defining one is pretty easy, and using it will reduce your amount of code.
operators = {
"+": add,
"-": sub,
"*": mul,
"/": div,
"pow": pow
}
This will define an object to hold all the operators that you can use.
Now all we need to do is use it.
Using operators.get
it's easy.
func = operators.get(operator, None)
if func is None:
print("Invalid operator!")
continue
Lovely and simple.
The main function is simple, just move everything in if __name__ == '__main__':
into a function.
With the operator addition you shouldn't really need to make smaller functions,
but it may be a good idea, making a function to get user input, could be a good idea.
But it's up to you.
If you did want to do both of these, you'd do something like:
def main(): while True: number1, number2, operator = get_user_input() func = operators.get(operator, None) if func is None: print("Invalid operator!") continue
def main():
while True:
number1, number2, operator = get_user_input()
func = operators.get(operator, None)
if func is None:
print("Invalid operator!")
continue
print(func(number1, number2))
if __name__ == '__main__':
main()
Just to note, you may not want to make get_user_input
.
Something that you may not know is you can use the builtin operators library.
This will allow you to remove all your definitions of add
, sub
, etc.
And will allow you to change operators to:
import operator
operators = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"pow": operator.pow
}
There's some history about Python's division, and that's why it's called truediv
, but if you haven't and won't use Python2, then you don't really need to know.