prev next 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Words and Numbers

What do you think happens when you try to do math with words?

>>> print 'red' + 'yellow'
>>> print 'red' * 3
>>> print 'red' + 3
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects

If you add two words, it sticks them together. If you times a word by 3, it makes three copies.

Python doesn't know how to add a word and a number, so it says "cannot concatenate 'str' and 'int' objects." A word that you put in quotes is just a string of letters called a "str" in python. Numbers that don't have a decimal point are integers and are called "int" in python.

You can't add a str and an int. But you can turn a number into a string if you use the str() function.

>>> print 'red' + str(3)