Loops

loops

Loops

Video Transcript

In this section, we're going to learn about loops. In Python, there are two types of loops: for loops and while loops.
A for loop looks like this:
for i in range(5):
  print(i)
# prints 0, 1, 2, 3, 4
These loops run for a specific, predetermined number of times. In the example above, the loop will always run exactly 5 times. To create a loop, we initialize it with the keyword for, then include a variable name. In the example above, we used the name i, which is common when making for loops, but the variable can have any valid variable name. Then, another keyword in comes after the variable. Finally, we use the range built-in function to specify the number of times to iterate. range takes as arguments either the number of times you want to repeat starting from 0, or the starting and ending values. Anything we want to repeat should be indented underneath this line, just like with an if statement or a function.
A while loop looks like this:
count = 0
command = ""
while command != "quit":
  command = input("Enter a command: ")
  count = count + 1
  print(f"Loop has repeated {count} times.")
These loops do not require a specific number of iterations. Instead, it works more like an if statement. After the while keyword, we include a condition. Before each iteration, the loop will check the condition, and if it's still true, it will continue to repeat. Once the condition is false, the loop stops. In the example above, the loop will continue to repeat until we enter the command "quit". Sometimes, when we want something to repeat forever, we will simply use the condition True so that the loop never stops.
Last section Next section