python字符串转float_混淆python - 无法将字符串转换为float

1586010002-jmsa.png

I got a value error and even if I try playing around with the code, it doesn't work!

How can I get it right? - I am using Python 3.3.2!

Here is the code:

PYT80.png

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.

This is the code in text format:

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")

解决方案

The problem is exactly what the Traceback log says: Could not convert string to float

If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.

If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.

The way most people would approach this problem is with a try/except (see here), or using the isdigit() function (see here).

Try/Except

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!")

Note that the latter will still return false if there are decimal points in the string

EDIT

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

The code's really simple:

It will keep trying to convert the input to a float, looping back to the beginning if it fails.

When eventually it succeeds, it'll break from the loop and go to the code you put lower down.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值