Learning Python: Loops

In Python there are two kinds of loops: while and for loops.

While loops

While loops are structured to continue looping while meeting some condition. In Python, it would be structured like the following example below:

count = 5
while count < 5:
  print(count)
  i += 1

For loops

In a for loop, you set the number of times to loop over a block of code. Unlike while loops, for loops do not require a variable to set and a condition to check:

numbers = [1, 3, 5, 7]
for number in numbers:
  print(number)

We can also use range() in order to specify the number of times to loop in a for loop:

numbers = [1, 3, 5, 7]
for number in range(04):
  print(number)

When using range(04) above, a sequence is created which starts 0 and goes to 4 since our array contains 4 items.

If we wanted to get the index in a for loop, we use the enumerate() function:

numbers = [1, 3, 5, 7]
for index, number in enumerate(numbers):
  print(index, item)

Using break and continue

We can interrupt both while and for loops using the break and continue keywords:

numbers = [1, 3, 5, 7]
for number in numbers:
  if number == 5:
    continue
  print(item)
numbers = [1, 3, 5, 7]
for number in numbers:
  if number == 5:
    break
  print(item)

This blog post was originally published on my blog Communicode, where I write about different tech topics.

CoduPython
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.