Different Types of Loops in Python

jabermudez11

Justin Bermudez

Posted on October 4, 2020

Different Types of Loops in Python

In this post I will show several loops in Python that you can utilize for your problems in python.

For Loop

For loop allows you to go over a dictionary, set, string, list, or tuple.

# loop over array example
array = [1, 2, 3, 4]
for x in array:
    print(x)

=> 1
=> 2
=> 3
=> 4

Loop Over String

string = "word"
for x in string:
    print(x)

=> w
=> o
=> r
=> d

Keep in mind, the printed out characters are of type string!

Loop over Set

Sets are unordered collections that have no duplicate elements

word = set("uniq")
for x in word:
    print(x)

=> u
=> n
=> i
=> q

Looping with range

Using range takes in a number to loop. You can use the length of an array for instance to iterate through the whole array.
Range will go by index so it will begin at 1 and end at the length - 1

array = [1, 2, 3, 4]
for i in range(len(array)):
    print("index:"i, ", value:", array[i])

=> index: 0 , value: 1
=> index: 1 , value: 2
=> index: 2 , value: 3
=> index: 3 , value: 4

While Loops

While loops continue to loop until the condition is met. Be careful using while loops because you can easily have an infinite loop.

counter = 0
while counter < 5:
    print(counter)
    counter += 1

=> 0
=> 1
=> 2
=> 3
=> 4

Not incrementing the counter here would result in an infinite loop and may timeout the program.

💖 💪 🙅 🚩
jabermudez11
Justin Bermudez

Posted on October 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024