Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Writing While Loops

In our last lesson, we focused on for loops, which are perfect for repeating tasks a known number of timesβ€”like processing every item in a list. Today, we'll explore Python's other essential loop structure, the while loop. This type of loop is designed for situations where the number of repetitions is unknown beforehand.

The core idea of a while loop is to repeat a block of code as long as a certain condition remains true. This is fundamental for building interactive programs, a key step toward your goal of creating chatbots. By the end of this lesson, you will be able to write while loops with clear and effective termination conditions to control program flow based on dynamic events, like user input.

When to Use a while Loop Instead of a for Loop

The key difference between for and while loops lies in how they decide to stop. A for loop runs for a pre-determined number of iterations, while a while loop runs until a condition is no longer met. This makes while loops ideal for tasks where you're waiting for something to happen.

The video "Python While Loops - Visually Explained" does an excellent job of clarifying this distinction with a practical example.

Python While Loops: Visually Explained

This video contrasts for and while loops and then demonstrates a classic scenario for a while loop: a user login system where you don't know how many attempts the user will need.

Please watch these two key segments: The Difference Between Them: Pay attention to the explanation of why a for loop isn't suitable for a login system. Simulating a Login System: Observe how the while loop continues to prompt the user as long as the password input is incorrect.

As the video highlighted, the login system is a perfect use case. You can't use a for loop because you have no idea if the user will get the password right on the first try or the tenth. The loop must continue while the input is wrong.

The Anatomy of a while Loop

The structure of a while loop is straightforward. It consists of the while keyword, a condition to be tested, a colon, and an indented block of code (the loop body).

while condition:



    # This code block will execute repeatedly
    # as long as the 'condition' is True.

Before each iteration, Python evaluates the condition. If it's True, the loop body runs. If it's False, the loop terminates, and the program continues with the code that follows. This cyclical process is visualized perfectly in the following flowchart.

This flowchart illustrates the logic of a `while` loop. The program enters the loop, tests a condition, and if it's true, executes the loop body before returning to test the condition again. The loop exits only when the condition becomes false.

To solidify your understanding of the syntax, let's turn to a clear, written explanation.

While Loops in Python – While True Loop Statement ...

This article from freeCodeCamp provides a concise definition of while loops and breaks down the syntax piece by piece.

Please read the first two parts of the article: The definition of a while loop, which reinforces its use for an unknown number of repetitions. The syntax breakdown, which explains each component of the loop structure.

The Infinite Loop and the Importance of an Exit Strategy

A while loop's greatest strength is also its greatest danger. If the condition never becomes false, the loop will run forever. This is called an infinite loop. To prevent this, your loop body must contain logic that eventually changes the condition to False. This is your loop's "exit strategy."

The "Bro Code" video provides an energetic walkthrough of this concept, showing what happens when you don't provide an exit and how to fix it.

While loops in Python are easy! ♾️

This video demonstrates the difference between a one-time if check and a continuous while check, highlighting the danger of infinite loops and the importance of having an exit strategy.

Watch the following segments: if vs while: See how replacing if with while creates a loop that repeatedly prompts for a name. Infinite Loop Danger: This part shows what happens when the code inside the loop can't change the loop's condition. Age Validation Example: Notice how prompting the user for input again inside the loop provides the necessary exit strategy.

The key takeaway is that something inside the loopβ€”like getting new user input or incrementing a counterβ€”must give the condition a chance to become false.

The while True and break Pattern

A very common and clean way to structure while loops, especially for interactive programs, is the while True pattern. Here, the loop's condition is always True, creating an intentional infinite loop. You then use an if statement inside the loop to check for a specific exit condition and use the break keyword to exit manually.

You encountered break in our last lesson with for loops; its function is identical here: it immediately terminates the loop.

This pattern is often preferred because it allows you to get input and then immediately test it, rather than needing a placeholder value before the loop starts. The "Visually Explained" video you watched earlier has a great section on this.

Python While Loops: Visually Explained

This part of the video refactors the login system example to use the while True and break pattern, demonstrating a cleaner and more direct structure.

Watch the final segment on this alternative syntax. Pay attention to how break is used to exit the loop from within.

This structureβ€”a while True loop containing a way to break outβ€”is the engine behind most simple conversational programs.

Application: A Simple Chatbot

Let's apply this directly to your interest in chatbots. The code below shows a simple bot that continuously listens for user input and responds based on keywords. It runs forever until the user says "bye".

This Python code defines a function `simple_bot` that uses a `while True` loop to create an interactive chat session. It takes user input, checks for keywords like 'hello', 'how are you', and 'bye' using `if/elif/else` statements, and prints a corresponding response. The loop terminates when the user's input contains 'bye'.

Let's break down how this works:

  1. while True: creates a loop that will run forever by default.
  2. user = input("You: ").lower() prompts the user for input and converts it to lowercase.
  3. The if/elif statements check if the user's input contains certain keywords.
  4. if 'bye' in user: checks for the exit condition. If it's True, the bot says goodbye, and the break statement terminates the while loop, ending the program.
  5. If no exit condition is met, the else block handles unknown input, and the loop repeats from the top, asking for input again.

This simple script is a foundational building block for the more complex NLP projects you're aiming for.

Your Turn: Practice with a while Loop

Now it's time to build a small program using these concepts.

Task: Create a simple number guessing game.

  1. At the start of your script, pick a secret number (e.g., secret_number = 7).
  2. Use a while True loop to continuously ask the user to guess the number.
  3. Inside the loop, convert the user's input to an integer.
  4. Use if/elif/else to check if the guess is too high, too low, or correct.
    • If the guess is too high, print "Too high, try again!"
    • If the guess is too low, print "Too low, try again!"
    • If the guess is correct, print "You got it!", and then use break to exit the loop.

This exercise will test your ability to create a while loop that runs until a specific condition is met, combining user input, type conversion, and conditional logic.




# Here's a starting point for your code.
# Fill in the logic inside the loop.

secret_number = 7

while True:
    guess_str = input("Guess a number between 1 and 10: ")
    guess = int(guess_str)
    



    # Your if/elif/else logic goes here...

print("Thanks for playing!")

Conclusion

In this lesson, you've added the powerful while loop to your Python toolkit. You now have two distinct methods for controlling repetition in your programs.

Here are the key takeaways:

  • while loops are for repetition where the number of iterations is unknown in advance. They run as long as a condition is True.
  • A while loop must have an exit strategyβ€”a way for its condition to eventually become Falseβ€”to avoid an infinite loop.
  • The while True and break pattern is a common and effective way to structure interactive loops, providing a clear exit point from within the loop body.
  • This structure is the core of simple interactive applications like the chatbot example we explored.

We have now concluded the first module on Python's foundational control flow. You are proficient with variables, conditionals (if/else), and both for and while loops. In our next lesson, we will begin Module 2 by exploring lists and dictionaries. These data structures will allow you to store and organize collections of information, enabling you to build much more capable and interesting programs.

Can't find a good explanation? Sign up and we'll make it for you

Sign up