Home Tutorials Tutorial on MicroPython while Loops

Tutorial on MicroPython while Loops

by shedboy71

In MicroPython, while loops allow you to execute a block of code repeatedly as long as a given condition is True.

This tutorial will guide you through the basics of using while loops, along with various examples to demonstrate common use cases.

Table of Contents:

1. Structure of a while Loop

The basic syntax of a while loop in MicroPython is:

while condition:
# Code to execute while the condition is True

The condition is a logical expression that is evaluated before every iteration of the loop. If the condition is True, the loop executes. If it becomes False, the loop stops.

Example: Simple while Loop

counter = 0

while counter < 5:
    print("Counter is:", counter)
    counter += 1

Output:

Counter is: 0
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4

In this example, the loop continues until the counter reaches 5.

2. Infinite while Loops

A while loop can run indefinitely if the condition never becomes False. This is useful for tasks where the loop needs to continue until a specific event happens (e.g., waiting for user input, managing microcontroller tasks, etc.).

Example: Infinite while Loop

while True:
    print("This loop will run forever")
To avoid infinite loops locking up your program, you should use control mechanisms such as break to exit the loop when needed.

3. Using break to Exit a while Loop

You can use the break statement to exit a while loop prematurely when a certain condition is met.

Example: Exiting a Loop with break

counter = 0

while True:
    print("Counter:", counter)
    counter += 1
    if counter == 3:
        print("Breaking the loop")
        break

Output:

Counter: 0
Counter: 1
Counter: 2
Breaking the loop

In this example, the loop runs indefinitely until the counter reaches 3, at which point break terminates the loop.

4. Using continue to Skip an Iteration

The continue statement is used to skip the current iteration of the loop and move to the next iteration without executing the remaining code in the loop body for that iteration.

Example: Skipping an Iteration with continue

counter = 0

while counter < 5:
    counter += 1
    if counter == 3:
        print("Skipping iteration 3")
        continue
    print("Counter is:", counter)

Output:

Counter is: 1
Counter is: 2
Skipping iteration 3
Counter is: 4
Counter is: 5

In this example, when the counter equals 3, the continue statement skips the print statement and moves to the next iteration.

5. else with while Loops

MicroPython allows an else block to be used with a while loop. The else block is executed once after the loop completes normally (i.e., without a break statement).

Example: Using else with while Loop

counter = 0

while counter < 3:
    print("Counter is:", counter)
    counter += 1
else:
    print("Loop finished successfully")

Output:

Counter is: 0
Counter is: 1
Counter is: 2
Loop finished successfully

If the loop is exited via break, the else block will not be executed.

6. Practical Example: Implementing a Counter

Here’s an example of a while loop that acts as a countdown timer. It counts down from a specific number to zero.

Example: Countdown Timer

import time

countdown = 5

while countdown > 0:
    print("Countdown:", countdown)
    time.sleep(1)  # Pause for 1 second
    countdown -= 1

print("Liftoff!")

Output:

makefile
Copy code
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!

In this example, the loop counts down from 5 to 0, pausing for one second between each iteration using the time.sleep() function.

7. Nested while Loops

You can also use a while loop inside another while loop. This is known as nesting. Nested loops are useful for tasks that require multiple levels of iteration, such as working with grids or multi-dimensional data.

Example: Nested while Loops

outer_counter = 1

while outer_counter <= 3:
    print("Outer loop iteration:", outer_counter)
    inner_counter = 1
    while inner_counter <= 2:
        print("  Inner loop iteration:", inner_counter)
        inner_counter += 1
    outer_counter += 1

Output:

Outer loop iteration: 1
  Inner loop iteration: 1
  Inner loop iteration: 2
Outer loop iteration: 2
  Inner loop iteration: 1
  Inner loop iteration: 2
Outer loop iteration: 3
  Inner loop iteration: 1
  Inner loop iteration: 2

In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop runs twice.

Complete Example: User Input with a while Loop

Here’s an example of a while loop that asks the user for input and keeps running until the correct answer is provided.

password = "abcd1234"

while True:
    user_input = input("Enter the password: ")
    if user_input == password:
        print("Access granted!")
        break
    else:
        print("Incorrect password, try again.")

In this example, the loop will continue asking for the password until the user provides the correct one.

Conclusion

The while loop in MicroPython is a powerful tool for executing a block of code repeatedly as long as a certain condition remains true. You now know how to:

Create basic while loops.
Handle infinite loops and break out of them using break.
Skip loop iterations with continue.
Use the else statement with while.
Write practical examples like countdown timers or user-input loops.
Understanding while loops is crucial for managing tasks that depend on repeating a block of code until a condition changes, especially in embedded and real-time systems.

You may also like

Leave a Comment