TypeError: cannot concatenate 'str' and 'int' objects

I am learning Python now, yay! Anyway, I have a little problem. Here I do not see the problem:

x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z 

But Python thinks differently - TypeError: cannot concatenate 'str' and 'int' objects .

Why is this so? I did not set any variable as a string ... as far as I can see.

+4
source share
2 answers

% has a higher priority than + , so s % y + z parsed as (s % y) + z .

If s is a string, then s % x is a string, and (s % y) + z tries to add a string (result s % y ) and an integer (value z ).

+13
source

You need to put brackets: (y+z)

+9
source

All Articles