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.