小编Dar*_*han的帖子

如何阻止用户仅输入"()"并在此之后仅输出"()"

我在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 input output

2
推荐指数
1
解决办法
77
查看次数

如何让用户在 python 计算器中重用先前计算的结果

我对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 input calculator python-3.x

0
推荐指数
1
解决办法
2015
查看次数

Python除以0错误

我目前正在使用这个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)

有什么方法可以防止用户将某些东西除以零?

python calculator

-3
推荐指数
1
解决办法
6875
查看次数

标签 统计

python ×3

calculator ×2

input ×2

output ×1

python-3.x ×1