2

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'

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)

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!

aimbire
  • 3,697
  • 1
  • 15
  • 28
Philosopher
  • 23
  • 1
  • 4

3 Answers3

7

float() returns a float, not converts it. Try:

line = float(line)
Marcelo
  • 9,916
  • 3
  • 43
  • 52
  • Thanks! I knew it was just a rookie mistake. Thanks for the quick response, as I was refusing to go to sleep until I solved the issue. – Philosopher May 14 '13 at 03:17
  • 1
    In fact, it is not possible to convert the value "in-place" - the language doesn't work that way. In Python, variables don't have types, but values do, and those types don't change. You just create new values representing the "converted" result. – Karl Knechtel May 14 '13 at 03:21
6

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)

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.'

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

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

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
  • This is the best solution. The name `line` is not appropriate for the resulting value. Even better would be `value = float(line)` and then continue with that. – glglgl May 14 '13 at 03:18
2

float(line) doesn't change line at all, so it is still a string. You'll want to use line = float(line) instead.

Simon
  • 10,679
  • 1
  • 30
  • 44