I was trying to use Python and I have created a short method:
def mul(x,y):
print(x*y)
by running mul(2,"23")
, I'm getting this outstanding output : 2323
Can someone explain this?
I was trying to use Python and I have created a short method:
def mul(x,y):
print(x*y)
by running mul(2,"23")
, I'm getting this outstanding output : 2323
Can someone explain this?
Because you're multiplying a string and an integer together:
>>> print '23' * 2
2323
Which is equivalent to '23' + '23'
.
Do mul(2, int('23'))
to turn '23'
into an integer, or just get rid of the quotation marks surrounding the 23
.
By the way, such function already exists in the operator
module:
operator.mul(2, 23)
In your multiplication function, first convert the input to int or float, depending on your requirement.
def mul(x,y):
print(int(x)*int(y))
Mulitplication is nothing but repetitive addition. In your case, if a string gets passed to your function, then it gets "added" that many times.
Also, if both the inputs are strings, then it will throw an error.
TypeError: can't multiply sequence by non-int of type 'str'
So it's safest to first convert them, before multiplying.
Multiplication of strings is not the same things as multiplication of numbers.
String multiplication does not implicitly convert to numbers, even if the string could be interpreted as such. Instead, the string is repeated, by the integer number given:
>>> 'foo' * 3
'foofoofoo'
If your method needs to multiply numbers, then make sure you get only numbers; use int()
or float()
to convert strings to numbers first.
It's because strings are not automatically converted to integers. Instead multiplication with string returns a string with multiple copies of the original string.
If you want to convert a string to an integer, you have to do it explicitly:
int("23")
In Python * operator could operate on both numbers and sequences i.,e either to multiply numbers:
2*3
6
or to repeat sequences:
2*'3' #string
'33'
[4,6]*2 #list
[4, 6, 4, 6]
(4,8)*2 #tuple
(4, 8, 4, 8)
#won't work with sets ([set type][2]) and dictionaries ([mapping type][3])
This is due to the fact that the operation to be performed by an operator depends upon the operands (objects) as we never declare the types of variables, arguments, or return values in Python.
putting together conditionals, input casting and math