Python:String不会转换为float

Python:String不会转换为float,第1张

概述参见英文答案 > Turn a variable from string to integer in python                                    3个 几个小时前我写了这个程序: while True: print 'What would you like me to double?' line = raw_input('> ') i 参见英文答案 > Turn a variable from string to integer in python                                    3个
几个小时前我写了这个程序:

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 ",resultprint 'Done! Enter to close'

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

float(line)

不起作用,并将行视为字符串而不是浮点数.我只做了一天python,所以它可能是一个新手的错误.谢谢你的帮助!

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

float_line = float(line)

更新:实际上更好的方法是首先检查输入是否是数字.如果它不是数字浮点(线)会崩溃.所以这更好 –

float_line = Noneif line.isdigit():    float_line = float(line)else:    print 'ERROR: input needs to be a DIGIT or float.'

请注意,您也可以通过首先强制转换行来捕获ValueError异常,然后处理它除外.

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

上述两种方法中的任何一种都将导致更强大的程序.

总结

以上是内存溢出为你收集整理的Python:String不会转换为float全部内容,希望文章能够帮你解决Python:String不会转换为float所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1191037.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存