问题描述
我当前正在使用以下Python代码:
I am currently using this Python code:
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
if False in [c in valid_chars for c in y]:
print("WARNING: Invalid Equation");
continue;
if(y == "end"):
break
exec(x)
print(x)
当用户执行以下操作时崩溃:9/0。错误:
It crashes when the user does something like this: 9/0. Error:
ZeroDivisionError: division by zero
有哪些方法可以防止用户将某物除以零?
What are some ways that will prevent the user from dividing something by zero?
推荐答案
您可以除了 ZeroDivisionError
之外
x = "1/0"
try:
exec(x)
except ZeroDivisionError:
print ("WARNING: Invalid Equation")
如果您使用的是Python 2.x,则输入数据将在此处进行评估
If you are using Python 2.x, the input data will be evaluated here itself
y = input(" >> ")
因此,在Python 2中.x,您应该使用
so, in Python 2.x, you should be using
y = raw_input(" >> ")
除此之外,您可以改进这段代码
Apart from that, you can improve this piece of code
if False in [c in valid_chars for c in y]:
valid_chars = set("0123456789-+/* \n") # We make this a set, because
if not all(c in valid_chars for c in y): # c in valid_chars will be in O(1)
就像@gnibbler一样,在评论部分建议,如果条件可以这样写,则相同
As @gnibbler, suggested in the comments section, the same if condition can be written like this
if any(c not in valid_chars for c in y): # c in valid_chars will be in O(1)
另一个建议是,无需使用分号来标记Python的行尾:)
Another suggestion would be, no need to use semi colons to mark the end of line in Python :)
这篇关于Python除以0错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!