Codes-R-Us
Codes-R-Us

Reputation: 15

I am getting an error when i try to do a Looping String in Python

New to Programming. Currently learning Python.

Code I wrote is:

       x = 0
       for x in "Helper":
       x = x + 1
       print(x)

But i get an error message saying "TypeError: cannot concatenate 'str' and 'int' objects on line 82"

Can anyone explain what i did wrong?

Upvotes: 0

Views: 252

Answers (2)

ToolmakerSteve
ToolmakerSteve

Reputation: 21357

As the comments say, don't use "x" for BOTH variables.

Do something like this:

x = 0
for c in "Helper":
   x = x + 1
print(x)

Result:

6

which is the number of characters in the string "Helper".

Upvotes: 2

x is initialized as int, but you are trying to add two different type (int, string) you should match each type

so try this

y = ""
for x in "Helper":
    y = y + x
print(y)

Upvotes: 0

Related Questions