The personal wiki of ...
Words and Numbers

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

> >> print 'red' + 'yellow'
redyellow > >> print 'red' * 3
redredred > >> 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)
red3 > >>

Next
Contact Us | Section Map | Disclaimer | RSS feed RSS FeedBack to top ^

Valid XHTML and CSS | Built on Foswiki

Page Updated: 20 Jan 2012 by ian. © Victoria University of Wellington, New Zealand, unless otherwise stated