Python:字符串不会转换为浮点数 [英] Python: String will not convert to float

查看:96
本文介绍了Python:字符串不会转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几个小时前写了这个程序:

I wrote this program up a few hours ago:

while True:
    print 'What would you like me to double?'
    line = raw_input('> ')
    if line == 'done':
        break
    else:
        float(line)              #doesn't seem to work. Why?
        result = line*2
        print type(line)         #prints as string?
        print type(result)       #prints as string?
        print " Entered value times two is ", result

print 'Done! Enter to close'

据我所知,它应该工作正常.问题是当我输入一个值时,例如 6,我收到 66 而不是 12.这部分代码似乎是:

As far as I can tell, it should be working fine.The issue is that when I input a value, for example 6, I receive 66 instead of 12. It seems like this portion of code:

float(line)

不起作用,将 line 视为字符串而不是浮点数.我只做了一天python,所以它可能是一个菜鸟错误.感谢您的帮助!

is not working and is treating line as a string instead of a floating point number. I've only been doing python for a day, so its probably a rookie mistake. Thanks for your help!

推荐答案

float(line) 不会就地转换.它返回 float 值.您需要将其分配回浮点变量.

float(line) does not convert in-place. It returns the float value. You need to assign it back to a float variable.

float_line = float(line)

更新:实际上更好的方法是首先检查输入是否为数字.如果它不是数字 float(line) 会崩溃.所以这样更好 -

UPDATE: Actually a better way is to first check if the input is a digit or not. In case it is not a digit float(line) would crash. So this is better -

float_line = None
if line.isdigit():
    float_line = float(line)
else:
    print 'ERROR: Input needs to be a DIGIT or FLOAT.'

请注意,您也可以通过首先强制转换 line 并在 except 中处理它来捕获 ValueError 异常.

Note that you can also do this by catching ValueError exception by first forcefully converting line and in except handle it.

try:
    float_line = float(line)
except ValueError:
    float_line = None

以上 2 种方法中的任何一种都会导致程序更健壮.

Any of the above 2 methods would lead to a more robust program.

这篇关于Python:字符串不会转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆