尝试将输入字符串转换为float

时间:2019-05-30 18:28:44

标签: python exception

如果输入的是字符串,我想请用户输入一个值,然后打印其长度。如果用户输入的是整数或小数,我想分别打印"Sorry, integers don't have length""Sorry, floats don't have length"

在尝试将输入转换为float或integer时,我正在使用异常。

这是我的代码:

c=input("enter a string: ")

def length(c):
    return len(c)

try:
    float(c)
    if float(c)==int(c):
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(length(c))

输出结果如下:

> enter a string: sfkelkrelte
11
> enter a string: 21
Sorry integers don't have length
> enter a string: 21.1
4

当我输入整数时,错误消息会正确显示,因为可以进行float()转换。但是,在浮点数的情况下,解释器将转到except块,尽管它应该已经执行了try块。

为什么会这样?

3 个答案:

答案 0 :(得分:1)

还为什么不将EAFP原则(What is the EAFP principle in Python?)应用于第二种条件?

select
    count(*) as cnt
from yourTable
where [date] > (select max([date]) from yourTable where [status] = 1)

我已经省略了检查s = input("Input: ") try: float(s) try: int(s) print("Sorry, you have entered an integer.") except: print("Sorry, you have entered a float.") except: print(len(s)) 的例外情况,因为您也没有在代码中检查它。但是,您应该看看How to properly ignore exceptions

答案 1 :(得分:0)

引发异常的部分是int(c)

c = "21.1"
print(int(c))
# ValueError: invalid literal for int() with base 10: '21.1'

一个较小的更改将为您解决此问题:

c="21.1"

try:
    float(c)
    if "." not in c: #<---- check if "." is in the string c AFTER conversion to float
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(len(c))
# Sorry floats don't have length

但是,盲目地捕获所有异常通常是一种不好的做法。这会在程序中触发except块的错误中产生意外的副作用。

仅捕获您期望的那个会更合适。

c="21.aakdjs1"

try:
    float(c)
    if "." not in c:
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except ValueError:
    print(len(c))
# 10

对于以后的调试,您随时可以print the exception

答案 2 :(得分:0)

将结果输入为字符串格式,因此将字符串转换为float,然后检查它是否为整数。将您的代码更改为:

old: if float(c) ==int(c):

new: if c.isdigit():

已更新:

enter a string: 21.0
Sorry floats don't have length