This blog post on coding for loops in Python is an excerpt from Level A of our Intro to Robotics program. Level A covers building circuits, using a Raspberry Pi, and writing common code commands in Python. It contains 18 lessons including 70+ videos and 45 projects and activities. Sample lessons and a full scope and sequence for Level A can be found here.
Sometimes in a program, you might want to do the same thing multiple times. For example, maybe you want to print the word ‘apple’ 50 times? You could write 50 print statements in a row, but there is a much better way to accomplish the same outcome using a loop. Loops are useful for doing the same thing in a program several times. A loop will cycle through whatever code is nested inside of it, as many times as you specify.
Here is an example of the code to set up a loop:
This code will create a variable called i which will initially be equal to 0. The variable does not need to be i, but programmers often use i as short for iterate, or to repeat a process over and over. Each time the loop runs, 1 will be added to the value of i. range(0,4) sets the range for the loop condition, so as long as i is between 0 and 4 the loop will continue to run.
Just like if statements or else statements, the loop statement must end in a colon, and the code to be executed by the loop must be indented to indicate it’s part of the loop.
In Lesson A-17 of our Intro to Robotics program, we teach you to code for loops in your Python programs. The image below is from the activity section of Lesson A-17. In that lesson you will build this four LED breadboard circuit, write the code for the GPIO pins connecting the breadboard and Raspberry Pi to shift from high to low to illuminate the LEDs, and then write a program that will turn on all four LEDs for one second and then a loop to make that happen 10 times in a row.
This blog post on coding for loops in Python is an excerpt from Level A of our Intro to Robotics program. Level A covers building circuits, using a Raspberry Pi, and writing common code commands in Python. It contains 18 lessons including 70+ videos and 45 projects and activities. Sample lessons and a full scope and sequence for Level A can be found here.