MicroPython Basics – While Loop, Operators, and User Input

In the last tutorial, we covered some very important topics to get you started with learning MicroPython so you can begin working with your Raspberry Pi Pico. There are still a few things to cover, but soon we will dive into the microcontroller itself and try out some fun projects!

Before we get started, recall the last lesson, where we covered some basic syntax, including how to print to the shell, how to group instructions through indentation, and how to write a for loop.

This time, we’re going to go over what’s known as a “while loop”, as well as conditionals and comparative operators. Woohoo! Let’s get started! 

Preparation

If your file “Indentation.py” is not currently open, go to Thonny, and open it from your Raspberry Pi Pico so that we can write in the editor.

🌍 Recommended Tutorial: Getting Started With Thonny – The Optimal IDE for the Raspberry Pi Pico

You can erase the current for loop and start fresh, but first, let’s try something.

A Note on Code Commenting

Make the current loop inoperable by highlighting the entire code and pressing Command+3 on Mac or Control+3 on a PC. 

💡 This is what we call “commenting out” your code, which basically turns the code off, so it doesn’t work without having to delete it altogether. Toggling code from being commented to uncommented will come in handy later when you start testing which lines of code do and don’t work.

Comments are also important to keep track of your thoughts and instructions so you can go back and refer to what you were trying to do with specific code as your projects become more complex.

A comment is preceded with a #, which will render anything you write to just be static text.

Ok, now that you understand commenting, let’s go ahead and delete the existing code since we know we aren’t going to need it again.

While Loops

While loops differ from for loops in that they are designed not to perform instructions a set number of times, but rather while certain conditions are met.

As such, while loops can sometimes result in what we call “infinite loops”. If the only condition we want to specify is that our program is to run, then we are creating an infinite loop.

In this case, we will want to make use of the Stop icon on the toolbar in Thonny.

The way we tell the program to run is simply by stating

while True:

So let’s try an infinite loop that will print "Loop running!" that we will have to use the Stop icon to, well, stop!

It should look like this:

while True:
    print("Loop running!")

Pretty simple, right? 🍎

Well, there is one tiny issue. A loop this simple can run too fast and chew up your computer’s resources, so we need to slow it down a bit so as not to overload our processor.

We do this by importing a library called Utime. We will get into more detail about libraries as we start programming the Pico in another installment, but for now, let’s just focus on the task at hand.

Go to the very top of your editor (line 1) and type:

import utime

Then we will add the while loop and include a delay plus another print function to show the loop ending:

while True:
    print("Loop running!")
    utime.sleep(1)
print("Loop finished!")

Click the Run icon to start the program again, and you’ll see "Loop running!" continuously printing in the shell with a 1 second delay between each print (that’s what’s happening when you use utime to sleep for (1)).

When you click the Stop icon, you’re actually interrupting the program, and the MicroPython interpreter will restart.

As a result, you’ll notice that the words "Loop finished!" never end up printing since the loop never ends until you interrupt the program, which stops it from ever getting to the final print instructions.

Womp, womp!

Inputs, Comparison Operators, and Conditionals

Cool! So now that you’ve written an infinite loop, let’s try another kind of while loop that checks for a certain condition. 👇

But first, let’s create an input so that we can experiment with making the condition we’re going to use either true or false.

In order to do that, we are going to define a new variable that will be checked for the trueness (or lack thereof) of the condition. For this new experiment, open a new file and save it as “Name_Test.py” then on line 1, type:

user_name = input("What is your name? ")

Notice there is a space after the question mark and before the closing quotes.

This is simply so that there will be a space between the question and your answer and is a common convention in Python.

Click the Run icon, and you’ll see the question appear in the shell, where you can type your answer right next to it. My name is Steve, so I’ll type that and hit Enter or Return

Notice nothing happens except you get a new command line in the shell.

That’s because you haven’t told MicroPython what to do with your name input. That’s what the next while loop is going to do. In this loop, we’re going to have a message that will print only if you have a certain name.

If not, then a different message will print and you’ll be re-prompted to input another name.

So how do we denote whether a name is equal to or different from the name checked for in the loop?

By using what we call comparison operators. The primary comparison operators we can use are:

Got it?

So that means that if we want to compare a name to our input, we need to write our loop using either the == or != operator.

And since we want to print a message and generate a new prompt any time the name doesn’t match, we want our loop to run whenever there is not a match.

But what if there is a match?

Well, we’ll give instructions for that outside of the loop with just a simple print command like before. Let’s use the name Bruce Wayne.

So under your user_name input in the editor write:

while user_name != "Bruce Wayne":
    print("You’re not Batman! Try again!")
    user_name = input("What is your name? ")
print("You’re Batman!")

Nice! That’s pretty much all you need to know about loops for now, but there is one other neat thing we can do with this comparison that will have a similar effect but doesn’t use a loop to check a condition’s trueness.

Conditional Statements

It’s called… yep, you guessed it – a conditional statement! 

These are used all over the place and use the terms “if” and “else“, returning a result if a condition is met or else returns something different.

In this case, it’s simpler than using the while loop, but the major difference here is that since we are not running a loop, you would have to click the Run icon again in order for another input to be considered.

For this example, we will simply write:

if user_name == "Bruce Wayne":
    print("You’re Batman!")
else:
    print("You’re not Batman!")

How cool! Try some different loops and conditionals on your own.

In the following tutorial, we’ll start looking at a basic Raspberry Pi Pico kit and its components. Until then, happy coding!

🌍 Keep Learning: Getting To Know Your Basic UCTRONICS Raspberry Pi Pico Kit