While loop in Python


A while allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while condition:
	instruction1
	instruction2
	...

Let's check an example:

counter = 1

while counter <= 4:
	print("I made a mistake")
	counter += 1
	
print("Finished!")

The code that goes inside a while loop has to be indented! In this code, the first unindented line print("Finished!") marks the end of the while loop's body.

And so this program prints:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable counter = 1

1. First iteration:
	a. Is counter <= 4 true? <=> Is 1 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 2
	
2. Second iteration:
	a. Is counter <= 4 true? <=> Is 2 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 3
	
3. Third iteration:
	a. Is counter <= 4 true? <=> Is 3 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 4
	
4. Forth iteration:
	a. Is counter <= 4 true? <=> Is 4 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 5

5. Fifth iteration:
	a. Is counter <= 4 true? <=> Is 5 <= 4 true? No.
	b. Exit the loop.
	
6. print("Finished!") => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the while loop in Python. The while loop is a fundamental control structure that allows a block of code to be executed repeatedly based on a given Boolean condition. Understanding how to use while loops is crucial for tasks that require repetitive actions, such as iterating over data, performing calculations until a condition is met, or automating repetitive tasks.

Understanding the Basics

The basic syntax of a while loop in Python is:

while condition:
    # code block to be executed

The condition is evaluated before each iteration of the loop. If the condition is True, the code block inside the loop is executed. This process repeats until the condition becomes False.

Let's look at a simple example:

counter = 1

while counter <= 4:
    print("I made a mistake")
    counter += 1

print("Finished!")

In this example, the loop prints "I made a mistake" four times and then prints "Finished!" after the loop ends.

Main Concepts

Key concepts to understand when working with while loops include:

Examples and Use Cases

Let's consider a few more examples to illustrate the use of while loops in different contexts:

Example 1: Counting Down

countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1

print("Liftoff!")

This loop counts down from 5 to 1 and then prints "Liftoff!"

Example 2: Summing Numbers

total = 0
number = 1

while number <= 10:
    total += number
    number += 1

print("Sum:", total)

This loop calculates the sum of numbers from 1 to 10 and prints the result.

Common Pitfalls and Best Practices

When using while loops, be mindful of the following common pitfalls:

Best practices for writing while loops include:

Advanced Techniques

Advanced techniques with while loops include using break and continue statements:

Using break to Exit a Loop Early

counter = 1

while counter <= 10:
    if counter == 5:
        break
    print(counter)
    counter += 1

print("Loop exited early")

This loop exits early when counter equals 5.

Using continue to Skip an Iteration

counter = 0

while counter < 10:
    counter += 1
    if counter % 2 == 0:
        continue
    print(counter)

This loop skips printing even numbers.

Code Implementation

Let's implement the assignment to print "I promise to learn coding" 5 times using a while loop:

# Initialize the counter variable
counter = 1

# Start the while loop
while counter <= 5:
    # Print the message
    print("I promise to learn coding")
    # Increment the counter
    counter += 1

Debugging and Testing

When debugging while loops, consider the following tips:

To test the loop, you can write test cases that verify the expected output:

def test_while_loop():
    import io
    import sys
    captured_output = io.StringIO()
    sys.stdout = captured_output

    # Run the loop
    counter = 1
    while counter <= 5:
        print("I promise to learn coding")
        counter += 1

    sys.stdout = sys.__stdout__
    output = captured_output.getvalue().strip().split('\n')
    assert output == ["I promise to learn coding"] * 5

test_while_loop()
print("All tests passed!")

Thinking and Problem-Solving Tips

When approaching problems that require while loops:

Conclusion

In this lesson, we covered the basics of while loops in Python, including their syntax, key concepts, common pitfalls, and best practices. We also explored advanced techniques and provided examples to illustrate their use. Mastering while loops is essential for writing efficient and effective code that involves repetitive tasks.

Keep practicing and experimenting with while loops to deepen your understanding and improve your problem-solving skills.

Additional Resources

For further reading and practice, consider the following resources: