Search code examples
pythonstringintegertypeerror

Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(name + age) TypeError: can only concatenate str (not "int") to str


I was writing the above code when I encountered an error can you help me?

name = 'mahbod'
age = 12
print(name + age)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(name + age)
TypeError: can only concatenate str (not "int") to str

Solution

  • It looks like you want to define two different variables: name and age. In that case, you need to define each of them on a different line:

    name = "mahbod"
    age = 12
    

    otherwise, here Python thinks that you are defining name as "Mahbod" age. In python, you can concatenate strings by separating them with a space, like this:

    >>> string = "Hello " "world"
    >>> print(string)
    Hello world
    

    so that's what Python is trying to do here, except that age is not a string, but a variable that you defined as 12, hence the confusion