Reputation: 489
I am having a problem with this very simple calculator script. If a user enters a letter or a word (such as: s, the), the system would crash. My idea is to make it print:
print ("WARNING: That is not a valid equation!")
When that happens. However, I cannot just make it see if y is an integer because otherwise, *, +, -,and / would not work. Also, I need a way for it to skip the
exec(x)
print(x)
part so it does not give me an error and crash the script. Thank you in advance!
Code (Python v3.3.0 - Mac OSX 10.8):
while True:
x = "x="
y = input(" >> ")
x += y
exec(x)
print(x)
Edit: After looking at raser's answer. This is what I changed it to. It is a mix of my previous code and both of his answers.
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
if False in [c in valid_chars for c in y]:
print("Errors!");
continue;
if(y == "end" or y == "End" or y == "exit" or y == "Exit" or y == "cancel" or y == "Cancel"):
break
exec(x)
print(x)
This is capable of doing equations such as: 7+9/3*2-3
Upvotes: 0
Views: 95
Reputation: 1638
you could catch the exception:
#!/usr/bin/env python
while True:
equation = raw_input(">> ");
try:
exec(equation);
except SyntaxError:
print("WARNING! That is not a valid function");
or if you want to detect anything not in 0-9*/-= you could just use a regex (which is probably overkill) or do something like this:
#!/usr/bin/env python
valid_chars = "0123456789-+/* \n";
while True:
equation = raw_input(">> ").strip();
if False in [c in valid_chars for c in equation]:
print("Errors!");
continue;
exec(equation);
Upvotes: 2
Reputation: 1001
Here's a really simple solution. Could be done with a lot less code, but it works (once each time you run the script):
cursor = 'calculator: '
x = raw_input(cursor)
if x.isdigit() == False:
print 'Please enter a number first'
y = raw_input(cursor)
operators = ['*', '+', '-', '/']
if y not in operators:
print 'Please enter one of the following operators: '.format(','.join(operators))
z = raw_input(cursor)
if z.isdigit() == False:
print 'Please enter a number after the operator'
else:
if y == '*':
print int(x) * int(z)
elif y == '+':
print int(x) + int(z)
elif y == '-':
print int(x) - int(z)
else:
print int(x) / int(z)
Upvotes: 0
Reputation: 3067
If you want to check if an input is an integer place a regex match statement before you run integer operations against it.
import re
while True:
x = "x="
y = input(" >> ")
if re.match("^[0-9]{0,}$", y):
x += y
exec(x)
print(x)
else:
raise TypeError("WARNING: That is not a valid equation!")
If you want to learn more about how regex works look here --> http://docs.python.org/2/library/re.html
Upvotes: 0