Postfix Calculator
Description
Analysis
### Take inputs for required 2 nums and 1 operator ###
num = input("[-] Num 1: ")
num2 = input("[-] Num 2: ")
op = input("[-] Operator: ")
### Check if op is a valid operator ###
### If no, then raise error ###
if not op in ['+', '-', '*', '/', '^']:
raise SyntaxError('Read token %s, expected operator' % op)
### Else, calculate new answer ###
print(f'\neval={num}{op}{num2}')
answer = eval(f'{num}{op}{num2}')
print(f"{answer=}\n")
num = input("[*] Num: ")
### Take inputs for more nums and operators ###
while num != '=':
op = input("[*] Operator: ")
### If not '=' or invalid, then calculate new answer ###
if not op in ['+', '-', '*', '/', '^']:
raise SyntaxError('Read token %s, expected operator' % op)
print(f"{answer} {op} {float(num)}")
answer = eval(f'{answer} {op} {float(num)}')
num = input("[*] Num: ")
### Output final answer ###
print(answer)Solution
Last updated