Skip to content

Instantly share code, notes, and snippets.



Last active Jun 18, 2016
What would you like to do?
Pfxcalc, a prefix notation calculator.
Programmed by zyabin101
This code is hereby released into the public domain
import ast
def lit_input(prompt):
Safely evaluate input. Only returns the following Python literal
structures: strings, numbers, tuples, lists, dicts, booleans, and 'None'.
Raises ValueError for malformed strings.
return ast.literal_eval(raw_input(prompt))
def lorr_input(prompt, result):
inputted = raw_input(prompt)
return result if inputted == "result" else ast.literal_eval(inputted)
# Initialization
x = None
# Print welcome message
print "Welcome to Pfxcalc. Type 'help' for more information."
# Main program loop
while True:
# Get user input
cmd = raw_input(">> ")
# Process input
if cmd == "quit":
elif cmd == "result":
print x
elif cmd == "help":
helpmsg = """
Pfxcalc is a prefix notation calculator.
Prefix notation, aka Polish notation, is a form of notation for logic,
arithmetic and algebra, like infix and postfix (reverse Polish)
The expression '+ 3 4' in prefix notation is as valid as '3 + 4' in
infix notation, as well as '3 4 +' in postfix notation.
Every computation starts with entering a command and the result is
printed *and* saved in a variable that can be recalled by entering
'result'. The variable can even be used as an argument for functions,
using the same command.
List of commands:
quit - self explanatory
result - recall the result variable
help - print this message
+ - add two numbers or sequences
- - subtract two numbers
* - multiply two numbers, or a sequence by a number
/ - divide two numbers
print helpmsg
elif cmd == "+":
x = (lorr_input("Left side addend? ", x) +
lorr_input("Right side addend? ", x))
print x # Implicitly output result
elif cmd == "-":
x = lorr_input("Minuend? ", x) - lorr_input("Subtrahend? ", x)
print x # Implicitly output result
elif cmd == "*":
x = (lorr_input("Left side factor? ", x) *
lorr_input("Right side factor? ", x))
print x # Implicitly output result
elif cmd == "/":
x = lorr_input("Dividend? ", x) / lorr_input("Divisor? ", x)
print x # Implicitly output result
print "Unrecognized command."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.