user12959766
user12959766

Reputation:

Why this code isn't running successfully?

Here is the simple code but I can't run! My code is:

name = input("What is your name? ")
print("My name is "+name+". "+"My name length is " + len(str(name)))

and Output is:

What is your name? Ali
Traceback (most recent call last):
  File "c:\Users\iamAl\Desktop\Python\main.py", line 2, in <module> 
    print("My name is "+name+". "+"My name length is " + len(str(name)))
TypeError: can only concatenate str (not "int") to str

Upvotes: 4

Views: 105

Answers (4)

Joaqu&#237;n
Joaqu&#237;n

Reputation: 350

If you want to print a number you should use , insted of +, in this case len() returns an int so if you want to print the string length you should first convert it to a string.

I suggest using .format to print various type of data:

name = input("What is your name? ")
print("My name is {}. My name length is: {}".format(name,len(str(name))))

Upvotes: 1

chepner
chepner

Reputation: 531165

As the other answers have pointed out, len returns an int, and you can't concatenate a str and an int with +.

However, you shouldn't be using + like this, as each + has to make a copy of its arguments. Use one of the string-formatting options instead, all of which will attempt to convert a non-str value to a str value for you, as well as creating only one string (for the result) in the process, not a series of temporary strings. For example,

print(f"My name is {name}. My name length is {len(name)}")

Upvotes: 2

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

You need to cast the int returned from len to an str, not cast str to str and then use len

print("My name is " + name + ". " + "My name length is " + str(len(name)))

Upvotes: 3

kojiro
kojiro

Reputation: 77107

Python is dynamic, but strongly typed. It won't let you add a string to an integer directly. You need to convert the types so they're compatible (meaning there has to be an addition operator that can handle adding them).

Possible solutions are:

  1. Cast one type to the other: str(len(name))
  2. Use a string interpolation method such as fstrings: f"My name is {name}. My name length is {len(name)}"

Upvotes: 3

Related Questions