Skip to content Skip to sidebar Skip to footer

Python If Else Loop Concatenate Objects

I have a simple Python if else loop but I get an error: prev_word += value_in cannot concatenate str and int objects prev_word = 0 print_variable = 0 for line in sys.stdin:

Solution 1:

This line is your problem:

prev_word = curr_word

On your first run through the loop, prev_word is the integer 0, and you convert value_in to an integer. So when you add value_in to prev_word, that succeeds because they are both integers. BUT you never convert curr_word to an integer, so when you set prev_word equal to curr_word, it becomes a string. And on your second time through the loop, prev_word += value_in fails because you can't add a string and an integer (that operation makes no sense).

I suggest not using the name prev_word for a variable that's supposed to hold integers, actually. Rename it to prev_number or something like that. Because it's obvious why you shouldn't assign curr_word to prev_number, but it's less obvious why you shouldn't assign curr_word to prev_word. Even through prev_word is really supposed to be a number, at least the way you're using it.

Solution 2:

You are reassigning prev_word inside your loop at the very end:

prev_word = curr_word

After this reassign, prev_word which is initialized to an int becomes a str and this causes your addition to fail.

With the power of dynamic types comes great responsibility. Good variable names are key :)

Post a Comment for "Python If Else Loop Concatenate Objects"