Little problem with the "+" operator

Joshua Marshall jmarshal at mathworks.com
Mon Mar 5 18:25:46 CET 2001


Steve Purcell <stephen_purcell at yahoo.com> wrote:
> Zamurai wrote:
>> variableOne = 500
>> myVariable = variableOne + "cool"
>> 
>> But I get the following error: "unsupported operand types for +"
>> 
>> Does someone know how to solve the problem?

> You can't add variables of different types together in Python and expect them
> to magically agree on a sensible result.

> So, you have to explicitly say:

>>>> variableOne = 500
>>>> myVariable = str(variableOne) + "cool"
>>>> myVariable 
> '500cool'
>>>> 

> Or,

>>>> variableOne = 500
>>>> myVariable = variableOne + int("cool")
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): cool
>>>> 


> This is infinitely more sane than:

> % perl -e 'print 500 + "cool"'
> 500

Comparing Python to Perl here doesn't seem very fair.  They're very
different languages.  In general, I'm surprised by the urgency with
which people often jump to compare them.



More information about the Python-list mailing list