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

发布于 2021-01-29 17:31:20

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

我该如何正确处理?-我正在使用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")
关注者
0
被浏览
164
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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

    尝试/除外

    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
    

    该代码非常简单:

    • 它将继续尝试将输入转换为浮点数,如果失败,则循环回到开头。
    • 如果最终成功,它将从循环中断开,然后转到您放下的代码。


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看