我遇到了一个值错误,即使我尝试使用代码,也无法正常工作!
我该如何正确处理? -我正在使用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
大多数人解决此问题的方法是使用
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/