我不能让我的“如果”命令正常工作

2024-09-27 07:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试添加两个数字,即使它们包含“-”或“.”,但如果我的命令有误,代码如下:

def add():
    print "\nAddition"
    print " "
    print "What is your first number?"
    preadd1=raw_input(prompt)
    print "What is your second number?"
    preadd2=raw_input(prompt)
    if preadd1.isdigit() and preadd2.isdigit():
        add1=int(preadd1)
        add2=int(preadd2)
        add_answer= add1+add2
        print " "
        print add_answer
        add()
    elif preadd1=="pike" or preadd2=="pike":
        pike()
    elif "-" in preadd1 or "." in preadd1 or "-" in preadd2 or "." in preadd2 and preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit():
        add1=float(preadd1)
        add2=float(preadd2)
        add_answer=add1+add2
        print ""
        print add_answer
        add()
    else:
        print "\nPlease enter two numbers."
        add()
add()

当我输入像“-sf”这样的非数字时,它返回错误:

ValueError: could not convert string to float: -sf

这对我来说毫无意义,因为这是一个确定的preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit()

请帮忙。你知道吗


Tags: orandanswerinadd数字floatreplace
3条回答

与其试图预测什么文本适合于float转换,不如这样做并处理结果。你知道吗

另见:EAFP

说明概念的不完整片段:

while True:
    try:
        text = raw_input()
        val = float(text)
        break
    except ValueError as e:
        continue

尝试将raw_input()包装到int()。您需要捕获错误,以便它不会到达if。你知道吗

你的问题中有太多的代码:

让我们将您的代码示例简化为您真正关心的内容:

preadd1 = "-sf"
preadd2 = "3"

if "-" in preadd1 or "." in preadd1 or "-" in preadd2 or "." in preadd2 and preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit():
    print "Shouldn't get here!"

我对你问题的看法:

以下是您的表达:

if "-" in preadd1 or "." in preadd1 or "-" in preadd2 or "." in preadd2 and preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit():

字符串中有一个-,所以整个表达式都是真的。你知道吗

真正的解决方案:

您应该看看这个问题,寻找各种正确的方法来测试字符串是否可以转换为浮点:Checking if a string can be converted to float in Python

相关问题 更多 >

    热门问题