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:
==
– equal to!=
– not equal to>=
– greater than or equal to<=
– less than or equal to>
– greater than<
– less than
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