Section 5: Loops
Welcome to Section 5! In this section, we will cover the basics of loops. Let's get started!
5.1 While
Coders often want to repeat code until a condition is met. To do this, we can use a while loop. Here is an example ...
a = 1
while a < 5:
print(a)
a = a + 1
The indented lines will keep on running until the condition in line 2 becomes False. In the last line, I increment a by 1 so the condition in line 2 will eventually become False and stop the looping. By the time a becomes 5, 1, 2, 3, and 4 would have been printed already. The syntax of while is the same as the syntax of if. However, the code will continue running until the condition is proven False. If the condition is not True to start with all the code will just be completely skipped, just like in an if statement.
Now that you have while loops down, let's move on to the next part!
5.2 For
Sometimes, we want to loop inside a variable to find all of the characters inside of it. We can use for loops to do this for any string. Here is an example ...
word = "coding123"
for character in word:
print(character)
This code will print every character in word on a new line. Line 3 will continue repeating until character has been every single character in word. The syntax for the for loop is the same as the syntax for a while loop, but instead of a condition, you need to have a new variable name, the keyword "in", and a string that it will loop through or a list (we will learn about them later) that it can loop through.
Now that you have for loops down, let's move on to the next part!
5.3 Range
We often want to loop through a list of numbers in a for loop. Range is a function that can automatically create a list of numbers that we can loop through in our for loops. Here is an example ...
for num in range(5):
print(num)
`The code above will print the numbers 0, 1, 2, 3, and 4 in consecutive lines. If range has only one input, it will loop through 0 until 1 below the input. The syntax for this is just to type range() and then put 1 plus the desired end value inside the parentheses. Here is an example with 2 inputs ...
for num in range(1, 5):
print(num)
The code above will do the same thing as the code with only one input, but this code will not start at 0, it will start at 1. The extra input, 1, specified the starting value for looping. All you have to do to add the starting value is type it in the parentheses before the ending value, and add a comma.
for num in range(1, 5, 2):
print(num)
The code above will print 1 and 3 on consecutive lines. This code will do this because the extra input, 2, means to increment by two. You will still start with 1 and end at 4, but we have to skip 2 and 4 because of the increment by two.
Now that you have range down, let's move on to the next section!
Sample Problems