How to let the user reuse a result from the previous computation in a python calculator

感情迁移 提交于 2019-12-02 09:06:32

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 _:

>>> def ans():
...     return _
... 
>>> 8 * 8
64
>>> ans() * 8
512
>>> def ans():
...     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:

>>> def ans():
...     try:
...         return _
...     except NameError:
...         return 0 # appropriate value
... 

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.

This:

valid_chars = "0123456789-+/* \n"
while True:
    x = "x="
    y = input(" >> ")
    x += y
    def ans():
        return z
    def ans():
        try:
            return z
    except NameError:
        return 0 # appropriate value
    if any(c not in valid_chars for c in y):
        print("WARNING: Invalid Equation")
        continue
    try:
        exec(x)
    except (SyntaxError, ZeroDivisionError):
        print ("WARNING: Invalid Equation")
    else:
        z = x
        print(x)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!