What are the types of loops we can create?


#1

Question

In the context of this lesson, what are the types of loops we can create in Python?

Answer

In Python, there are two main types of loops you can create, which are a for in loop, and a while loop.

With a for loop, we can iterate over a sequence of items, such as a list, dictionary, or even a string. The syntax is as follows

for item in list:
  ...

for letter in string:
  ...

A while loop is a loop which will keep executing a block of code until its given condition becomes False. When writing a while loop, be careful with the condition, so that it eventually will become False, otherwise, it can be stuck in an infinite loop.

# This will be stuck in an infinite loop!
i = 0
while i < 5:
  print(i)

# This will eventually terminate
i = 0
while i < 5:
  print(i)
  i += 1