I’ve been doing some CodingBat Python practice problems and while messing around in vscode I found something I don’t quite understand.
When using the following bit of code the output will be: “112123”
def string_splosion(thing:str) -> str:
word = ""
x = 0
for x in range(len(thing)):
word = word + thing[0:x+1]
return word
print(string_splosion("123"))
however, if instead of adding 1 to x inside of the string thing I do it after with x+=1 the word equation is finished it cuts off the 123 at the end so the output looks like this:“112”
Here is what the code looks like as described above:
def string_splosion(thing:str) -> str:
word = ""
x = 0
for x in range(len(thing)):
word = word + thing[0:x]
x+=1
return word
print(string_splosion("123"))
Why does it work this way? I assume it has something to do with the way x is getting counted differing between the two. I did some tests where I added print(x) before and after x+=1 and x increased as expected, but when adding print(x) to the first bit of code before and after word = word + thing[0:x+1] x did not change at all