I’m writing a simple calculator program in Python. Here’s the code:
string_calculation = ''
list_of_operators = ('+', '-', '*', '/', '**', '//', '%')
x = True
while x:
com = input('Enter a number or operator. When finished, type "=": ')
if com == '':
continue
if com != '0' and com[0] == '0' and com[1] != '.':
print('Enter a valid number.')
print()
continue
if com == '=':
if string_calculation == '':
quit()
if string_calculation[-1] in list_of_operators:
print('Missing number for the last operator.')
print()
continue
try:
eval(string_calculation)
except:
print()
print('ERROR: DIVIDE BY 0')
quit()
break
no_number = False
if string_calculation == '':
no_number = True
if not no_number:
if string_calculation[-1] in list_of_operators and com in list_of_operators or string_calculation[-1:-2] == com or string_calculation[-1:-2] in list_of_operators:
print('Enter a valid calculation.')
print()
continue
if com in list_of_operators:
if no_number:
print('Enter a number first.')
print()
continue
string_calculation += com
else:
try:
float(com)
except:
print('Enter numbers or operators.')
print()
continue
if not no_number:
try:
float(com) and float(string_calculation[-1])
except:
pass
else:
print('You cannot enter back to back numbers.')
print()
continue
string_calculation += com
print(string_calculation)
final_answer = eval(string_calculation)
if str(final_answer) == string_calculation:
quit()
print(final_answer)
This code makes it so you can input any number, then any operator, then any number, (and so on), and it should give you the answer to that calculation. Everything works fine apart from the fact that when I
input (any number), then (any operator), then 0, it gives me the output of ‘You cannot enter back to back numbers.’ This should only happen when the user inputs two numbers in a row. Not when you input, for example, “0” then “+” then “0”. When I input “1” then “+” then “1”, or any numbers other than 0, the code works as expected.
I was messing around with the code and randomly decided to switch the order in line 50 from “float(com) and float(string_calculation[-1])” to “float(string_calculation[-1]) and float(com)” and to my surprise, it actually fixed the issue. But now I’m just confused and don’t know why it worked. This line of code is supposed to check whether the current input is a number and whether the previous input was also a number. If both are numbers, then it skips the except and goes to the else statement, where it prints the message of not being able to input back to back numbers. I don’t understand why switching around the two float functions in the and statement solved the issue of getting the ‘You cannot enter back to back numbers.’ message when inputting (any number) then (any operator) then “0”.
Dexter Hot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1