python - 令人困惑的python-无法将字符串转换为float

标签 python error-handling

我遇到了一个值错误,即使我尝试使用代码,也无法正常工作!

我该如何正确处理? -我正在使用Python 3.3.2!

这是代码:

如您所见,该程序会询问您可以走多少英里,并根据您键入的内容给出响应。

这是文本格式的代码:

print("Welcome to Healthometer, powered by Python...")
miles = input("How many miles can you walk?: ")
if float(miles) <= 0:
    print("Who do you think you are?!! Go and walk 1000 miles now!")
elif float(miles) >= 10:
    print("You are very healthy! Keep it up!")
elif float(miles) > 0 and miles < 10:
    print("Good. Try doing 10 miles")
else:
    print("Please type in a number!")
    miles = float(input("How many miles can you walk?: "))
    if miles <= 0:
        print("Who do you think you are?!! Go and walk 1000 miles now!")
    elif miles >= 10:
        print("You are very healthy! Keep it up!")
    elif miles > 0 and miles < 10:
        print("Good. Try doing 10 miles")

最佳答案

问题恰恰是Traceback日志所说的:Could not convert string to float

  • 如果您的字符串只有数字,那么python足够聪明,可以执行您要尝试的操作,并将字符串转换为浮点数。
  • 如果您的字符串中包含非数字字符,则转换将失败并显示错误信息。

  • 大多数人解决此问题的方法是使用try/except(请参阅here)或使用isdigit()函数(请参见here)。

    试试/除
    try:
        miles = float(input("How many miles can you walk?: "))
    except:
        print("Please type in a number!")
    

    Isdigit()
    miles = input("How many miles can you walk?: ")
    if not miles.isdigit():
        print("Please type a number!")
    

    请注意,如果字符串中有小数点,则后者仍将返回false

    编辑

    好的,我暂时将无法与您联系,因此我将发布答案以防万一。
    while True:
        try:
            miles = float(input("How many miles can you walk?: "))
            break
        except:
            print("Please type in a number!")
    
    #All of the ifs and stuff
    

    该代码非常简单:
  • 它将继续尝试将输入转换为浮点型,如果输入失败则循环回到开头。
  • 如果最终成功,它将从循环中断开并转到您放下的代码。
  • 关于python - 令人困惑的python-无法将字符串转换为float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736589/

    相关文章:

    python - 如何使用带有 *args 的映射在 python 函数调用中解包元组

    Python Scrapy - 从 mysql 填充 start_urls

    mysql - sql fiddle 可以处理的内容有限制吗? sql fiddle 不编译任何东西并且不返回任何错误消息

    c++ - 错误 : anachronistic old-style base class initializer [-fpermissive]

    python - 无效的URL给出regexmatchError并且在pytube程序中给出无效的URL时不引发错误

    java - 错误调用方法

    python - AttributeError : 'Tensor' object has no attribute 'lower' when applying Global MaxPooling instead of GlobalAveragePooling [duplicate]

    python - Python 中的文件索引(使用二叉树?)

    python - 为什么 Python 属性需要同名的辅助函数?

    python - 用 Python 解析 90MB 的数据存档