tags:

views:

66

answers:

5

Possible Duplicate:
Python - Parse String to Float or Int

I want to know how I can multiply raw input by a certain number. This is what I have so far:

dog = raw_input("Dog:")
multiply = (dog * 2)
print multiply

The result is (let's say I chose 10 as the raw input):

1010

I know why I'm getting this, because python is taking it as a string. How do I take it as a float instead?

A: 

You can use a string as an argument to the int or float command:

dog = raw_input("Dog:")
multiply = (int(dog)*2)
print multiply

Of course, you need to be prepared to handle conversion errors if, for example, the user entered "poodle" instead of a number.

Relevant documentation:

Bryan Oakley
A: 

raw_input returns a string. Convert it to int before you multiply. Of course, you should provide a check that user input can be converted to int.

dog = raw_input("Dog:")
dogI = int(dog)
multiply = (dog * 2)
print multiply
pyfunc
A: 

Try taking int(dog) to get the integer value of a string of numbers. For example:

>>> int("2")
2
>>> type(int("2"))
<type 'int'>
Wyatt Anderson
+4  A: 
dog = float(raw_input('Enter the number'))

Since raw_input returns a string, that is why we cast it to a float. You can of course use an int if you want.

EDIT: Since others have mentioned that you might need to handle input errors, I have updated.

Consider a simple function:

>>> def input_num():
        while True:
            try:
                num = int(raw_input('Enter a number: '))
            except ValueError:
                print 'Not a valid number'
                continue
            break
        return num


>>> x = input_num()
Enter a number: 10
>>> print x
10
>>> x = input_num()
Enter a number: a
Not a valid number
Enter a number: 10
sukhbir
+1  A: 
dog = raw_input("Dog:")
multiply = (float(dog) * 2)
print multiply
Nathon