-1

I'm getting the error "TypeError: cannot concatenate 'str' and 'int' objects" when i try running this for some reason

I'm following a tutorial on YouTube and it seems to work for them

name = "Tan"
age = 20
print("Hello my name is " + name + " and i am " + age + " years old")
age = 17
name = "Taq"
print("Hello my name is " + name + " and i am " + age + " years old")

The age is meant to be assigned as 20 and then as 17 but it just gives an error.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • You can't add an int to a string. Make the int a string first, then add it – G. Anderson Nov 06 '19 at 17:56
  • Also, if you're learning Python right now, stop learning Python 2.7 and learn Python 3. Python 2.7 will [stop being officially supported](https://www.python.org/dev/peps/pep-0373/#id2) next year. – Ari Cooper-Davis Nov 06 '19 at 19:57

3 Answers3

2

You need to convert your integers to strings before you can concatenate them:

a = 'I can eat '
b = 5
c = ' biscuits.'
print(a + str(b) + c)

Or you could use string formatting to approach this problem:

a = 5
print('I can eat {} biscuits.'.format(a))
Ari Cooper-Davis
  • 3,374
  • 3
  • 26
  • 43
1

Here, do it like this: print("Hello my name is " + name + " and i am " + str(age) + " years old") You need to cast the age into a string before you concatenate.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
1

You have to convert the integer age to string before concatenating ... + str(age)+...

nitin3685
  • 825
  • 1
  • 9
  • 20