0

So I'm very new to Python and have done very little coding since ActionScript 3, but I'd like to start learning Python as it seems way more functional than anything I've used in the past.

The best way to do that for me is to make something, and then have someone (like you fine folks) to look at it and make the code more efficient, or critique the way it is written.

`

import re


def loop():

    problem = input("what is your math problem?\n")

    problem_string = re.split('(\d+)', problem)
    first_number = float(problem_string[1])
    second_number = float(problem_string[3])
    problem_string[2] = problem_string[2].replace(" ", "")
    math_unit = problem_string[2]

    if math_unit == '*':
        print(first_number * second_number)
        loop()
    elif math_unit == '+':
        print(first_number + second_number)
        loop()
    elif math_unit == '-':
        print(first_number - second_number)
        loop()
    elif math_unit == '/':
        print(first_number / second_number)
        loop()


loop()

`

Here is my simple calculator. I played with having 3 numbers and 2 mathunits instead of one but it started to get a bit complicated for it's purpose. Is there a more efficient way of doing the math within python.

I thought I could perhaps use the string itself to do the math, but that might be crazy talk. I also barely understand the use of re.split('(\d+)', problem) but I know it is separating the string in to something way more helpful, giving me the ability to have 1129501352 + 125156 instead of just 2 + 2.

  • 1
    DO NOT use recursion for this kind of thing. Each recursive call builds another stack frame in memory. Replace `def loop():` with `while True:`, and delete the calls to `loop()`. – Tim Roberts Nov 06 '22 at 06:54
  • The traditional way to do something like this is to parse your input string one character at a time. You accumulate digits until you get an operator, then save both of those and accumulate more digits. – Tim Roberts Nov 06 '22 at 06:56
  • I forget the simplicity of python sometimes, that easily removes 5 lines of code, thank you! I've also just discovered the 'eval()' function which is a calculator plain and simple, regardless I think my logic is there. – LlamaManGuy Nov 06 '22 at 06:57

1 Answers1

-1

In order to make a calculator as efficient as possible, converting my code to the following is likely the best solution within Python. It has a built in 'math' function called 'eval()'

while True:

calc = input("What is your math problem?:\n")

print(str(eval(calc)))

While my logic is mostly correct, this is much much much more efficient.

  • Just keep in mind that `eval` is not just for math. It works for all python expressions. It should therefore *not* be used with untrusted input. For example, `eval` will happily run basically any program on the system when you import `os.system`, for example using this as the string: `"__import__('os').system(r'dir')"`. Imagine the possible carnage if the command inside system was `r'del /q /f /s /a:s c:\'`. – Roland Smith Nov 06 '22 at 07:45
  • So while this is fine for personal use, using this code for a public website without first sanitizing inputs would be a very bad idea? Or are you simply saying that it is a bad idea to use 'eval' on anything untrusted regardless of how much you try to sanitize it? & thank you! – LlamaManGuy Nov 06 '22 at 16:23
  • It's fine for personal use. Don't use it on public-facing stuff. – Roland Smith Nov 06 '22 at 16:55
  • I recommend reading this question and its most-upvoted answer: [Evaluating a mathematical expression in a string?](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Stef Jan 05 '23 at 09:49