I don't know how to multiply in Python.
If I do this:
price = 1 * 9
It will appear like this:
111111111
And the answer needs to be 9
(1x9=9
)
How can I make it multiply correctly?
This question is related to
python
string
multiplication
I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:
>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9
So make sure the first operand is an integer (and not a string), and it will work.
Should work:
In [1]: price = 1*9
In [2]: price
Out[2]: 9
Use integers instead of strings.
make sure to cast your string to ints
price = int('1') * 9
The actual example code you posted will return 9
not 111111111
In [58]: price = 1 *9
In [59]: price
Out[59]: 9
You cannot multiply an integer by a string. To be sure, you could try using the int (short for integer which means whole number) command, like this for example -
firstNumber = int(9)
secondNumber = int(1)
answer = (firstNumber*secondNumber)
Hope that helped :)
Only when you multiply integer with a string, you will get repetitive string..
You can use int()
factory method to create integer out of string form of integer..
>>> int('1') * int('9')
9
>>>
>>> '1' * 9
'111111111'
>>>
>>> 1 * 9
9
>>>
>>> 1 * '9'
'9'
It's the difference between strings and integers. See:
>>> "1" * 9
'111111111'
>>> 1 * 9
9
Source: Stackoverflow.com