Reputation: 489
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 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)
Error: "Unexpected Indent" for except NameError
What did I do wrong and how can I fix this? Thanks
Upvotes: 1
Views: 2944
Reputation: 19
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)
Upvotes: 1
Reputation: 5629
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
...
Upvotes: 6
Reputation: 1060
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.
Upvotes: 1