参见英文答案 Turn a variable from string to integer in python3个 几个小时前我写了这个程序: while True: print 'What would you like me to double?' line = raw_input(' ') if line == 'done': break else: float(line) #doesn't
几个小时前我写了这个程序:
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.看起来这部分代码:
float(line)
不起作用,并将行视为字符串而不是浮点数.我只做了一天python,所以它可能是一个新手的错误.谢谢你的帮助!
float(line)不会就地转换.它返回浮点值.您需要将其分配回float变量.float_line = float(line)
更新:实际上更好的方法是首先检查输入是否是数字.如果它不是数字浮点(线)会崩溃.所以这更好 –
float_line = None if 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
上述两种方法中的任何一种都将导致更强大的程序.