Skip to content

Instantly share code, notes, and snippets.

@MuhammedAnasm4444
Last active August 16, 2020 11:20
Show Gist options
  • Save MuhammedAnasm4444/3bae9e555658d50c684c53a4c4a10bff to your computer and use it in GitHub Desktop.
Save MuhammedAnasm4444/3bae9e555658d50c684c53a4c4a10bff to your computer and use it in GitHub Desktop.
Calculator in Python without using eval()
# Take inputs from user as list
# Then apply this loop
# for example user input is (1+2-3)
# the list is = ['1','+','2','-','3']
# it check the opperands in list[2] and do the operation b/w list[1] and list[3] and pops all first three elements in
# list add the new value in list[1] and operation goes on ......
for i in range(len(value)):
try:
if value[1] == '+':
xsum = float(value[0]) + float(value[2])
xsum = str(xsum)
print(xsum)
value.pop(0)
value.pop(0)
value.pop(0)
print(value)
value.insert(0,xsum)
print(value)
elif value[1] == '-':
xdifference = float(value[0]) - float(value[2])
xdifference = str(xdifference)
value.pop(0)
value.pop(0)
value.pop(0)
print(value)
value.insert(0,xdifference)
print(value)
elif value[1] == '*':
xmultiply = float(value[0]) * float(value[2])
xmultiply = str(xmultiply)
value.pop(0)
value.pop(0)
value.pop(0)
print(value)
value.insert(0,xmultiply)
elif value[1] == '/':
try:
xdivision = float(value[0]) / float(value[2])
xdivision = str(xdivision)
value.pop(0)
value.pop(0)
value.pop(0)
print(value)
value.insert(0,xdivision)
print(value)
except Exception:
label_value.set("not defined")
division_error = True
value.pop(0)
value.pop(0)
value.pop(0)
print(value)
value.insert(0,xdivision)
print(value)
elif value[1] == '%':
xpercentage = 100 * float(value[0])/float(value[2])
except Exception:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment