Why does multiplication repeats the number several times?

user1704332 picture user1704332 · Oct 4, 2012 · Viewed 170k times · Source

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?

Answer

Rohit Jain picture Rohit Jain · Oct 4, 2012

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'
  • If both operand is int, you will get multiplication of them as int.
  • If first operand is string, and second is int.. Your string will be repeated that many times, as the value in your integer 2nd operand.
  • If first operand is integer, and second is string, then you will get multiplication of both numbers in string form..