The first time I got stuck in an infinite Python loop…

Priscila Brey
Analytics Vidhya
Published in
7 min readMay 17, 2021

…and everything I did to fix it before getting stuck in another infinite loop, as well as other learnings from my first code project.

One of my first Python lessons (on Colt Steele’s Python 3 Udemy Bootcamp) included a quick tutorial on how to make an infinite While Loop, and how to never do it again unless the objective was to fry my computer.

Now, the While Loop is a wicked tool to carry under your belt. When used with a functioning break statement, a simple While Loop can be the basic structure for some pretty cool applications. And by “break statement” here, I just mean any statement that will break the loop, not the python Keyword “break”.

The concept is simple; write conditional logic, and code will be executed while said condition is true. Once the statement is no longer true, the code will stop. Easy enough, right?

Credit to the creator of this meme for the LOLs. Unfortunately, I don’t know who that is. If it happens to be you, send me a message so I can link your page!

I stumbled across my first infinite loop while writing a quick script for a game of Rock, Paper, Scissors.

The game — usually played by humans — consists of two players flashing hand gestures (fist for rock, open hand for paper, and peace sign for scissors) after counting to three or saying “rock, paper, scissors, go!!!!!”.

The winner is decided based on some very simple rules: rock beats scissors, paper beats rock, and scissors beat paper. More on the origins of the game here.

Since I didn’t know how to build a GUI, my game was going to be played through the computer terminal and would only be text-based.

The initial setup was easy, I needed to get the user to input their choice, I needed the computer to make a choice, and I needed to declare a winner based on the game rules. To do this, I used Python’s Random Module for the computer to “pick an object”, and stored the choice in a variable. I also declared a variable for the user’s choice and a series of If Statements that decided the winner of the round.

By the time I had written the main structure for my game, I was feeling pretty confident and decided to add some ✨extras✨.

An early version of the script looked like this:

An early version of the game that allowed users to pick a nickname, quit at any point during the match, and play multiple rounds while scoring points.

I added an input that let users pick a nickname and used it throughout the game, I also set up some variables to keep track of scores and added the option to quit the game.

At this point, there were a number of things I wanted to change about the script (unexpected behaviour struggle is real), but my main thing was that I wanted users to be able to play again without having to restart the file.

Queue the catastrophe.

I created a variable called “active_game” and set its value to “y”*, then wrapped a while loop around my main structure and ended it with a prompt for the user to decide whether they wanted to continue playing or exit out. The user’s input would update the active_game variable accordingly.

*I think it’s worth mentioning that there are better and probably more pythonic ways to define the active_game variable, but at the time I was terrified by the idea of getting stuck in an infinite loop, and steering clear of the booleans seemed like the best way to stop it from happening. Little did I know…

Anyway, below is the code that got me stuck in the loop(s). See if you can spot the mistake:

Perhaps seeing the result helps:

Did you catch it?

Don’t worry if you didn’t, it only took me like 1.5 hours of re-running the same script and pulling weird faces, all while getting annoyed and stressed about the idea of my computer breaking forever. Thankfully though, computers come with a “Quit Terminal” option that ends active processes.

https://www.monkeyuser.com/

All jokes aside, this really did take me a long time to solve. The mistake I made was not indenting the line where the user has to choose whether to play again or not. If you look closely, the prompt is outside of the outer loop and with nothing being used to break out, and no new inputs being added, the only true statement is that one score is higher than the other, meaning the winner will be printed out endlessly.

Confusing much? Let’s break it down.

In my outer loop I tell the program to run as long as active_game is equal to “y”. I then define an inner loop that continues to run as long as both scores are less than the winning_score, in this case, 3. In the next steps the answers given by both the user and the computer are compared, and points are stored in their individual score variables.

Once either of the score variables hits 3, the inner loop is broken, “Game Over” is printed and a new If Statement tells the program to print the winner based on who has the highest score. But the option to edit the value of active_game is never given.

The key here is the outer loop, we said it would run for as long as active_game is equal to “y”. Since we never asked for the variable to be edited, there is no way for the loop to be exited.

The iconic Monica to express how we all feel right now.

So, how did I fix it? I pressed tab and placed the ending statement within the loop. Rookie mistake? Yes, but the process of figuring out why my code was failing was a wild ride. I re-read my script 100+ times, I read every thread on stack overflow and I even questioned if I should retake the loop module from the course. It wasn’t until I explained my script line by line to someone else that I realized where the error was.

The next thing to do was to re-run the script to make sure the loop was working. I executed the command and began playing the game. All was going well until I reached the winning score and was asked if I wanted to play again. I tried once for no and the program shut down. Excellent. I restarted the game, reached the end and this time when prompted, I tried “y”. Can you guess what happened next? Take another look at the script above if it helps.

Yep, I was prompted again, “Do you want to play again? y/n:”. So, I hit “y” and was prompted again. This went on for a few minutes. I was baffled.

I went back to my script and began reading it out loud, trying to replay the logic in my head. And there it was, in line 19.

while computer_score < winning_score and player_score < winning_score:

The game loop was only executed while both scores were less than 3. Because I had already played, and I added a point to the scores every time a player won a round, at least one of the scores was no longer less than 3. Therefore, the option of playing another round was impossible.

The fix for this was to reset the score variables when the game ended. Then, users could choose to play again and actually do it.

At last my game worked!! I had everyone around me try it and made some changes based on feedback. I also added some interactions from the computer, inspired by old video games I had played as a kid.

There were also a few unexpected behaviours, like game winners being decided when the user pressed quit. I added statements to avoid that and also removed the option of “tied game” since it was never going to be the case: If users only get points for winning a round, it won’t be the case that both users have 3 points by game end.

I learned a bunch of things while working on this super easy project. I originally wanted to avoid spending too much time on it because I felt it was too simple to be relevant, but boy was I wrong!

The main takeaway from this experience for me, was that there is never a project that is beneath us. There’s an opportunity to learn something new in every line of code.

I also learned that the learning path is never over, and that needing to refresh knowledge on certain concepts is more than okay, but doubting yourself isn’t. Fear will make you stray from the path of logic (remember that crazy active_game variable? a bool value probably wouldn’t have been the cause of a broken script), making mistakes is natural! The key is to stay cool. And also, I’ve since started working in tech and I’ve seen senior developers make silly mistakes hundreds of times. There’s nothing to be afraid of.

Perhaps for next time I’ll try to build something with a GUI, we’ll see. In the meantime the code for my Rock, Paper, Scissors game can be found here.

Thanks for reading!

--

--