n
4

My first real program broke because I didn't understand loops

About three weeks ago, I wrote a simple Python script to rename a bunch of image files in a folder. I thought it was working fine until I ran it and it just kept going, creating weird file names like 'photo_copy_copy_copy.jpg'. I watched it for a minute before I had to force it to stop. The problem was my while loop. I set it to run while a counter was less than the number of files, but I forgot to actually increase the counter inside the loop. So it just ran forever on the first file. I felt pretty dumb, but fixing it was just adding one line: 'counter = counter + 1'. It made me realize how important it is to test small parts of your code before you run the whole thing. Has anyone else had a loop go totally wrong on them?
3 comments

Log in to join the discussion

Log In
3 Comments
xenawhite
xenawhite2d ago
I used to skip testing small parts until an infinite loop taught me better.
10
riverw85
riverw8522d ago
That copy file name is a perfect example of what happens. I had a similar issue with a for loop in JavaScript that kept adding the same item to a list. It's a right of passage. Wade_perez is right about the feeling, but it's not always about a task without a clear way forward. Sometimes you just forget the update step, like you did. My fix was also just one line, moving where I pushed the item to the array. It really teaches you to trace through the logic step by step on paper first.
5
wade_perez
wade_perez22d ago
Oh man, that's the classic infinite loop! I see the same thing happen with people who get stuck doing the same task over and over without a clear way to move forward.
4