我尝试添加两个数字,即使它们包含“-”或“.”,但如果我的命令有误,代码如下:
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()
请帮忙。你知道吗
与其试图预测什么文本适合于
float
转换,不如这样做并处理结果。你知道吗另见:EAFP
说明概念的不完整片段:
尝试将
raw_input()
包装到int()
。您需要捕获错误,以便它不会到达if
。你知道吗你的问题中有太多的代码:
让我们将您的代码示例简化为您真正关心的内容:
我对你问题的看法:
以下是您的表达:
字符串中有一个
-
,所以整个表达式都是真的。你知道吗真正的解决方案:
您应该看看这个问题,寻找各种正确的方法来测试字符串是否可以转换为浮点:Checking if a string can be converted to float in Python
相关问题 更多 >
编程相关推荐