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.
Top comments (0)