我在python上相当新,所以我对它不太了解:/.但是,这是我的代码:
valid_chars = "0123456789-+/*ans() \n";
while True:
x = "x="
y = input(" >> ")
x += y
def ans():
return z
def ans():
try:
return z
except NameError:
return 0 # appropriate value
if any(c not in valid_chars for c in y):
print("WARNING: Invalid Equation")
continue
try:
exec(x)
except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
print ("WARNING: Invalid Equation")
else:
z = x
print(x)
Run Code Online (Sandbox Code Playgroud)
这有效,但并不完美.如果用户键入"()",则输出"()".如何阻止它输出"()"并说"警告:无效的公式"?提前致谢!
更新:
如果我使用"if not"功能,它会起作用吗?例:
if not(y == "()"):
continue
except:
print ("WARNING: Invalid Equation")
Run Code Online (Sandbox Code Playgroud)
我知道这不起作用但我怎么能解决它还是有更好的想法?谢谢!
我对python相当陌生,所以我对此知之甚少。我做了一个计算器,我希望它接受:
ans()
Run Code Online (Sandbox Code Playgroud)
输入。目前,如果存在 [0-9 */-+] 以外的其他内容,则有一部分会阻止程序执行输入,因此它不会崩溃。我该怎么做
ans()
Run Code Online (Sandbox Code Playgroud)
代表上次输入的方程的输出,所以我可以输入如下内容:
>> 8*8 #last input
64 #last output
>> ans()*2 #current input
128 # current output
Run Code Online (Sandbox Code Playgroud)
希望我正确解释了所有内容,这是我的代码:
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
if any(c not in valid_chars for c in y):
print("WARNING: Invalid Equation")
continue
try:
exec(x)
except (SyntaxError, ZeroDivisionError):
print ("WARNING: Invalid Equation")
else:
print(x)
Run Code Online (Sandbox Code Playgroud)
更新:我添加了答案中推荐的几行,但它不会运行(我还修复了缩进):
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ") …Run Code Online (Sandbox Code Playgroud) 我目前正在使用这个Python代码:
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)
Run Code Online (Sandbox Code Playgroud)
当用户执行类似这样的操作时崩溃:9/0.错误:
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)
有什么方法可以防止用户将某些东西除以零?