Learn
Loops
Infinite Loops

We’ve iterated through lists that have a discrete beginning and end. However, let’s consider this example:

my_favorite_numbers = [4, 8, 15, 16, 42] for number in my_favorite_numbers: my_favorite_numbers.append(1)

What happens here? Every time we enter the loop, we add a 1 to the end of the list that we are iterating through. As a result, we never make it to the end of the list! It keeps growing!

A loop that never terminates is called an infinite loop. These are very dangerous for your code!

A program that hits an infinite loop often becomes completely unusable. The best course of action is to never write an infinite loop.

Note: If you accidentally stumble into an infinite loop while developing on your own machine, you can end the loop by using control + c to terminate the program. If you’re writing code in our online editor, you’ll need to refresh the page to get out of an infinite loop!

Instructions

1.

Suppose we have two lists of students, students_period_A and students_period_B. We want to combine all students into students_period_B.

Write a for loop that goes through each student in students_period_A and adds it to the end of students_period_B.

2.

Inside the for loop, after appending student to students_period_B, print student.

3.

Let’s suppose you made a typo in the body of your for loop. Oh no! We will go through a few steps to see what happens when you end up with an infinite loop and how you fix it:

  1. Inside the for loop, change the object of the append statement from students_period_B to students_period_A.

  2. Run this code. What do you notice happens? Over the run button, notice the loading circle is continuing without anything happening. This is an infinite loop! To end this program we must refresh the page. (Note: The reason this loop is infinite is that we’re adding each student in students_period_A to students_period_A which would create a never-ending list of all the student names.)

  3. After refreshing your page, you should see that the run button is back. Now get rid of the change we made that caused an infinite loop by changing the object of the append statement back to student_period_B.

  4. Run your code again. This time your loop should not be infinite, and it should run to completion.

4.

Great job! We have now seen what happens when you run an infinite loop and how we can fix them! Revel in the safety of your code, and how it doesn’t crash your browser. Run it one final time to make sure it is working as expected.

Folder Icon

Sign up to start coding

Already have an account?