This is my first ever Python program. I thought I would make a calculator that performs 5 operations: add, subtract, divide, multiply, power. I am aware Python has its own power function, called "pow", but I have defined my own power function for practice.
I've taken the input as a single string, and then I've tried to separate the numbers from the operator in my for loop, using what little Python I currently know. Perhaps this is the section of my code that could be made cleaner, above all else?
Coming from Java, my first instinct was to use a switch statement to handle each operator case. I quickly realised Python doesn't have switch statements, but I discovered that dictionaries are apparently a good substitute. But maybe there is a better way of handling each operator case?
And obviously, I should have error handling, but let's just ignore that detail for now.
val = str(input("Calculate: "))
# get first number, second number, and operator, from string
foundOp = False # has the operator been found?
a, b = "", "" # first and second number
for char in val:
# concatenate digits
if char.isdigit():
if foundOp:
b = b + char
else:
a = a + char
# skip spaces
elif char == " ":
continue
# find operator
elif not char.isdigit():
foundOp = True
op = char
# convert a and b into int
a, b = int(a), int(b)
# compute a ^ b
def power(a,b):
original_a = a
for i in range(1,b):
a *= original_a
return a
calc = {
"+": a + b,
"-": a - b,
"*": a * b,
"/": a / b,
"^": power(a,b)
}
print(calc[op])
print(eval(input("Calculate:").replace('^', "**")))
. It simply reads the input, converts it to a string of corresponding Python expression, and then evaluates and prints the result. \$\endgroup\$eval
is basically never a good idea. \$\endgroup\$eval
is generally not good but in this case it is appropriate IMO. It is useful for handling code-like strings. Newcomers do not need to use it often but it would be better for them to know the existence of the built-in. \$\endgroup\$eval
of user input is classically awful, and is in no way appropriate. Useast
instead. \$\endgroup\$ast
is only for parsing literals, not evaluating an entire expression. Usingeval
for user input is not recommended primarily due to potential security issues. This post shows how to makeeval
safe when needed. A basic expression evaluator is actually one primary use case for theeval
function. \$\endgroup\$