简体   繁体   中英

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?

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.

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
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

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

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 :)

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM