Skip to content Skip to sidebar Skip to footer

How To Let The User Reuse A Result From The Previous Computation In A Python Calculator

I am fairly new at python so I don't know much about it. I made a calculator and I want it to accept a: ans() input. Currently, there is a part that stops the program from executi

Solution 1:

If you want to use your program in the python interpreter, you can use a simple trick. The interpreter stores the last output in the special variable _:

>>>defans():...return _...>>>8 * 8
64
>>>ans() * 8
512
>>>defans():...return _...>>>8 * 8
64
>>>ans() * 2
128
>>>

Just remember, that _ can raise a NameError if there hasn't been any output so far. You can handle it with something like that:

>>>defans():...try:...return _...except NameError:...return0# appropriate value...

Solution 2:

In the Python REPL loop _ represents the last result; however, this may not be the case in your calculator.

Try something like

valid_chars = "0123456789-+/*()ans \n";result = None

...

result = eval(x.replace('ans()',str(result))

You probably want something better than valid_chars though, and parse for correct expressions. Also, as an aside, what you are evaluating are expressions not equations.

Hope this helps.

Solution 3:

This:

valid_chars = "0123456789-+/* \n"whileTrue:
    x = "x="
    y = input(" >> ")
    x += y
    defans():
        return z
    defans():
        try:
            return z
    except NameError:
        return0# appropriate valueifany(c notin valid_chars for c in y):
        print("WARNING: Invalid Equation")
        continuetry:
        exec(x)
    except (SyntaxError, ZeroDivisionError):
        print ("WARNING: Invalid Equation")
    else:
        z = x
        print(x)

Post a Comment for "How To Let The User Reuse A Result From The Previous Computation In A Python Calculator"