0

I just started Automate The Boring Stuff, I'm at chapter 1.

myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + lengthofname)

I ran this, it gave me Can't convert 'int' object to str implicitly. My reasoning at line 3 is that I want the variable myname to be converted into an integer and then plugged into line 4.

Why would this be an erroneous way of coding?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
sam h
  • 19
  • 1
  • 1
  • 2
    Look at http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly. Please google before you post. – Henry Prickett-Morgan Nov 13 '16 at 04:37
  • Use comma to seperate arguments in `print()` and `print()` will convert them to string automatically - `print ('your name is this many letters:', lengthofname)` – furas Nov 13 '16 at 04:58

3 Answers3

4

When you have print ('your name is this many letters:' + lengthofname), python is trying to add an integer to a string (which of course is impossible).

There are 3 ways to resolve this problem.

  1. print ('your name is this many letters:' + str(lengthofname))
  2. print ('your name is this many letters: ', lengthofname)
  3. print ('your name is this many letters: {}'.format(lengthofname))
Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39
Nic
  • 78
  • 1
  • 6
2

You have problem because + can add two numbers or concatenate two strings - and you have string + number so you have to convert number to string before you can concatenate two strings - string + str(number)

print('your name is this many letters:' + str(lengthofname))

But you can run print() with many arguments separated with comma - like in other functions - and then Python will automatically convert them to string before print() displays them.

print('your name is this many letters:', lengthofname)

You have only remeber that print will add space between arguments.
(you could say "comma adds space" but print does it.)

furas
  • 134,197
  • 12
  • 106
  • 148
0

Your code seems to be Python 3.x. The following is the corrected code; just convert the lengthofname to string during print.

myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + str(lengthofname))
Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97