patternpythonModerate
Simple python calculator
Viewed 0 times
simplecalculatorpython
Problem
I'm very new to Python, and so I'm trying to learn it by doing simple programs, like a calculator. But I don't know if this is the "Pythonic" way to do it, or if I am making beginner errors.
So could someone please tell if something is wrong with it, and how to improve it?
Here is some sample input and output:
Here is the code
So could someone please tell if something is wrong with it, and how to improve it?
Here is some sample input and output:
Enter the first number: 2
Enter the second number: 10
Enter an operator (valid operators are +, -, *, / and pow): pow
1024.0Here is the code
#A basic calculator which supports +, -, *, / and pow
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
def pow(a, b):
return a ** b
if __name__ == "__main__":
while True:
try:
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
except:
print("That is not a number!")
continue
operator = input("Enter an operator (valid operators are +, -, *, / and pow): ")
#Check if user operator is a valid one
if operator == "+":
func = add
elif operator == "-":
func = sub
elif operator == "*":
func = mul
elif operator == "/":
func = div
elif operator == "pow":
func = pow
else:
print("Invalid operator!")
continue
#Print result
print(func(number1, number2))Solution
For a beginner this is pretty good.
But, there are three glaring problems with it.
Starting with (2), a dictionary holds a key value pair.
If 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.
This will define an object to hold all the operators that you can use.
Now all we need to do is use it.
Using
Lovely and simple.
The main function is simple, just move everything in
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:
Just to note, you may not want to make
Something that you may not know is you can use the builtin operators library.
This will allow you to remove all your definitions of
And will allow you to change operators to:
There's some history about Python's division, and that's why it's called
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.
If 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!")
continueLovely 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
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.Code Snippets
operators = {
"+": add,
"-": sub,
"*": mul,
"/": div,
"pow": pow
}func = operators.get(operator, None)
if func is None:
print("Invalid operator!")
continuedef 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()import operator
operators = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"pow": operator.pow
}Context
StackExchange Code Review Q#127205, answer score: 13
Revisions (0)
No revisions yet.