Introduction to Python continues with Module Three, starting with loops. SoloLearn will only focus on two loops, but I teach three loops to Level M students at Coding with Kids. Today's post will show you for, while, and for each loops.
By the end of this post, you will have a better understanding of loops and why they are important in code. You will be able to create each type of loop in your code. Next week, the third part of this module will discuss conditionals.
Iteration Review
Before diving into all of these loops, let's take a minute to expand on iteration. Iteration is a part of good control flow. Iterations solve real problems by combining comparison operations and iterations.
Looping is the most popular example of iteration. SoloLearn describes iteration as automating the tasks that need to be repeated. In real life, people see assembly lines made of different stations that repeat tasks to create a final product.
For example, if you went to a pizza shop, some stations repeat parts of a pizza over and over again. You might find:
- areas for making dough
- putting the entire pizza together. These could be stations for sauce and putting on all the pizza toppings
- an area near the oven where someone manages what pizzas are coming in and out of the oven.
- an area for taking pizzas and putting them into boxes so they are out for delivery or pick up.
- dishwashing area that cleans pans and equipment needed for other stations.
Computers have many imaginary assembly lines, like the pizza shop, that repeat lots of different tasks. They have a lot of things that they are trying to do, so repeating tasks need to be simple, fast, and have no errors. That also means less work for you because you will have less code to write.
Level M students see this by looking at examples where there is code with no iteration and one with it to decide which one they prefer. Using iteration helps you write code only once, and having the computer repeat it for you instead of you copying and pasting the same code over and over again.
While Loops
The first loop you need to learn is the while loop. It is the first loop that Level M students learn when they start learning about Python. While loops repeat only if a condition is true.
Once the condition of the loop becomes false, the loop stops. To create a while loop, start with the while keyword. Next, put your condition.
This condition will be true and keep the loop repeating. Finally, you put your colon.
i = 0
while i < 5:
print(i)
i = i + 1
This code sample has a variable with an integer assigned to it. Underneath is a while loop that will run if i is less than 5, followed by a colon. As this condition is true, it will print i and update the counter variable by adding one. When this condition becomes false, the loop will stop.
For Loops
The second loop you will use often in code is for loops. A for loop repeats code for a specific number of times. To create a for loop, you begin with the for keyword.
Next, you put a counter variable. This will keep track of the iterations you make or how many times you repeat your code. After that, you put the range function.
The range function tells the computer how many times it needs to repeat the code. Put a number in parentheses. Finally, close the parentheses and put the colons.
for x in range(10):
print("Couch!")
This code sample features a for loop. After the for keyword, there is the x counter variable to track the iterations. The range function is going to repeat 10 times. Underneath the for loop, the code indented inside will print a text.
For Each Loops
A for each loop is another kind of for loop, but this loop isn't covered in this course. When I teach Level M students, for each loops are part of the curriculum and act differently from a for loop. So I'm giving them a separate section.
A for each loop still has some similarities with a for loop as it iterates through things and uses the for keyword. However, the big difference is that for each loop goes through the elements of a list or an array. You can see them when a program needs to iterate through data structures (i.e. lists, arrays, dictionaries).
To create a for each loop, you start with the for keyword. Next, you will create a temporary variable. This will hold the values for the data structre being looped through.
Temporary variables give loops a chance to check the changes being made. They can even delete values. SoloLearn encourages students to think of them as a temporary name being used to access each element in a data structure.
After the temporary variable, put the in keyword followed by the data structure you will be looping through. The data structure is the structure holding the values that the computer needs to look at.
for sprite in sprite_list:
sprite.set_x(random.randint(-220, 220))
sprite.set_y(random.randint(-220, 220))
This code sample is an example of a for-each loop that Level M students create in one of their games. This for each loops start the same as a for loop with the for keyword. The temporary variable in this code is sprite.
After “in”, this loop will iterate through a list called sprite_list. Indented on the next two lines is the code that will be repeated. In this sample, the code will set the x and y for the sprite by randomly picking a number between -220 and 220.
Best Practice for Loops
Now that you know how to create each type of loop, let's talk about some best practices you need to keep in mind as you work with this concept.
Indentation
Indentation is something every developer needs to be careful with since it can create big problems in code. Pay attention to how you indent your code. Indenting incorrectly can confuse the computer and create errors because the computer will assume the code might not be inside or outside a loop.
Loops can repeat multiple statements. They all need to be indented. As you make loops in your code, make sure the code that needs to be repeated is inside the loop.
That means you will need to indent your code. Anything that isn’t going to be repeated doesn’t need to be indented and goes outside of your loop. After the loop is finished, the computer will continue to execute statements in sequence.
game_over = True
score = 0
player_one = codesters.Sprite("person1")
player_two = codesters.Sprite("person2")
while game_over = False:
# code for loop goes inside.
print("Hello World")
function greeting():
# function code goes inside
print("This is a function")
greeting()
The code sample above showed some variables, a function, and a while loop. The print statement inside the while loop is indented, telling the computer that this code needs to be repeated inside the loop. When I start my function at the bottom, the function is not indented, so it isn’t inside the loop.
A common mistake new developers make with indenting their code is using the space bar. Avoid this in your code. You will want to use the tab key to make sure you indent correctly.
Indentations are the spaces at the beginning of the lines. Python isn’t picky about how many spaces you use. You can use 2 or 4 spaces, depending on your needs. You just need to make sure you are consistent.
Level M students use Codesters to get their feet wet in Python. One of the nice things about Codesters is that it includes color guides to help students double-check their indentation. As they indent their code, the text editor creates colorful bars to show students what goes inside a loop or function. Your editor might not include a color guide like Codesters, but I still encourage Coding with Kids students to double-check how they are indenting their code.
Colons and Counter Variables
Colons and counter variables play an important part in setting up while and for loops. The colon is the last thing you need to add when you set up a loop. When you press Enter in your text editor, some will immediately start indenting your code because they know you are creating a loop.
If your text editor doesn't do this, you will still need to indent your code. For loops and while loops both use counter variables to keep track of how many times the code is being repeated. Every time the loop repeats, the counter variable will update in each iteration. When developers initialize (set up) code, they will set a value outside the loop for where the loop should begin.
When should I use a for loop or a while loop?
It can be tough knowing when to best use a for loop or a while loop. However, SoloLearn tells students to think about the iterations. If you know how many iterations you need to do, a for loop would work best for you.
If you don't know how many iterations you need to make, a while loop works the best. For example, a developer might want to use a while loop to ask a user to enter a password correctly. If you have to print a label for 50 items, a for loop would work best for you.
Beware Infinite Loops!
One of the things you will often hear about loops is the dreaded infinite loop. Infinite loops are common in loops, but they can create big problems in your code. Infinite loops happen when the condition remains true forever, so it never stops repeating.
That might sound like a good thing, but infinite loops are bad in code because they can break your program. So you will want to be careful when to use a while loop.
Top comments (0)