令人困惑的python - 无法将字符串转换为浮点数 [英] Confusing python - Cannot convert string to float
问题描述
我收到了一个值错误,即使我尝试玩弄代码,它也不起作用!
I got a value error and even if I try playing around with the code, it doesn't work!
我怎样才能做到正确?- 我使用的是 Python 3.3.2!
How can I get it right? - I am using Python 3.3.2!
这是代码:
如您所见,该程序会询问您可以步行多少英里,并根据您输入的内容给出响应.
As you can see, the program asks for how many miles you can walk and gives you a response depending on what you type in.
这是文本格式的代码:
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
The problem is exactly what the Traceback log says: Could not convert string to float
- 如果您有一个只有数字的字符串,python 足够聪明,可以执行您正在尝试的操作并将字符串转换为浮点数.
- 如果您有一个包含非数字字符的字符串,转换将失败并出现您遇到的错误.
大多数人解决这个问题的方法是使用 try/except
(参见 此处),或使用 isdigit()
函数(参见 这里).
The way most people would approach this problem is with a try/except
(see here), or using the isdigit()
function (see 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
Note that the latter will still return false if there are decimal points in the string
好的,我有一段时间不能回复你,所以我会发布答案以防万一.
Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.
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 - 无法将字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!