如何让用户重用python计算器中先前计算的结果 [英] How to let the user reuse a result from the previous computation in a python calculator
问题描述
我是python的新手,所以我对此不太了解。我做了一个计算器,我希望它接受:
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()
输入。当前,如果没有[0-9 * /-+]以外的内容,有一部分可以阻止程序执行输入,因此不会崩溃。我该怎么做
input. Currently, there is a part that stops the program from executing an input if there is something other than [0-9 */-+] so it does not crash. How can I make
ans()
表示上次输入的方程式的输出,因此我可以输入以下内容:
represent the output of the equation last entered so I can enter something like this:
>> 8*8 #last input
64 #last output
>> ans()*2 #current input
128 # current output
希望我能正确解释所有内容这是我的代码:
Hopefully I explained everything correctly and here is my code:
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
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:
print(x)
更新:我添加了在答案中建议的几行,但它没有运行(我也修复了缩进):
Update: I added several lines that were recommended in the answers but it would not run (I also fixed the indents):
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
def ans():
return _
def ans():
try:
return _
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:
print(x)
错误:除了NameError之外,意外缩进
Error: "Unexpected Indent" for except NameError
我做错了什么以及如何解决?谢谢
What did I do wrong and how can I fix this? Thanks
推荐答案
如果要在python解释器中使用程序,可以使用一个简单的技巧。解释器将最后的输出存储在特殊变量 _
中:
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
>>>
请记住, _
可以提高 NameError
如果到目前为止没有任何输出。您可以使用类似的方法处理它:
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
...
这篇关于如何让用户重用python计算器中先前计算的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!