Reputation: 271
I am completely baffled at this seemingly simple problem that I have. I want to define a function that will take the input, which can be a str or int and double it. For example, if the input is 'foo'
, then the output will be 'foofoo'
. Likewise, if the input is (9), the output will be 18. Can somebody point me in the right direction?
Here is what I have so far:
def double(x):
"""returns two times a number if input is a number, returns double the size of the string inputted, if input is a string
str -> str; int -> int"""
if x is :
return x*2
if x is :
return x*2
Upvotes: 0
Views: 4385
Reputation: 52000
What about:
def double(x):
return x+x
or
def double(x):
return x*2
Both should work as:
+
operator is overloaded to perform concatenation when arguments are strings;*
operator is overloaded to "duplicate" when one argument is a string.As Python is dynamically typed, the choice of the real operation performed will be made at run-time, depending the type of the operands.
More formally, to quote the documentation:
The
*
(multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.[...]
The
+
(addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated.
If you're curious, from the sources or Python3.3.6/Objects/abstract.c
(The code for PyNumber_Mul
is quite comparable) :
PyObject *
PyNumber_Add(PyObject *v, PyObject *w)
{
PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
if (result == Py_NotImplemented) {
PySequenceMethods *m = v->ob_type->tp_as_sequence;
Py_DECREF(result);
if (m && m->sq_concat) {
return (*m->sq_concat)(v, w);
}
result = binop_type_error(v, w, "+");
}
return result;
}
As you can see, the interpreter will first try to perform an addition using the special method __add__
defined for the left operand. If this one returns NotImplemented
, it will try to interpret the left operand as a sequence and perform a concatenation.
Upvotes: 5
Reputation: 16711
Just multiply the input by two. If it is a string, it will concatenate twice. If it is a number, it will double.
user = raw_input('Enter input: ')
print user * 2
Look at the Python Documentation. This is taken straight from it.
Strings can be concatenated (glued together) with the
+
operator, and repeated with*
:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Upvotes: 1