Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does multiplication repeats the number several times?

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?

like image 204
user1704332 Avatar asked Oct 04 '12 18:10

user1704332


2 Answers

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 operands are ints, you will get multiplication of them as int.
  • If one operand is an int and the other is a string, then the string will be repeated the number of times specified by the int.
like image 87
Rohit Jain Avatar answered Oct 27 '22 00:10

Rohit Jain


Should work:

In [1]: price = 1*9

In [2]: price
Out[2]: 9
like image 41
Joseph Victor Zammit Avatar answered Oct 27 '22 00:10

Joseph Victor Zammit