DEV Community

Hadijja Musekwa
Hadijja Musekwa

Posted on

Using loops in python

I recently learnt how to work with loops in Python, and it unlocked a level of comfort and ease while working with the program, since the unnecessarily long and difficult process became easier.

I learned about for loops, while loops, break, continue and enumerate.

Loops solve the problem of writing the same lines of code many times by allowing a block of code to be executed repeatedly, either for a specific number of times or while a condition remains true.

for Loops
This is used when I want to iterate through a sequence of items, as demonstrated below.

Python takes each item from the list, stores it in the variable name, and then the indented code runs for each item.

using range
This function is used with for loops when I want to repeat something a certain number of times.

it was important to learn that for example, range(5) starts at 0 and stops before 5.

When I want to control exactly how many times an operation occurs, I can specify a starting point: *range(1, 6)
*

The range function, range(start, stop, step), defines the starting point, the stopping point and the increment between each number in the sequence.

while loop
A while loop continues executing as long as a condition is true.
The problem is that the number never changes, so the condition stays true and creates an infinite loop.
To avoid an infinite loop, we increment the value in each loop. This creates a false condition and ends the loop, as demonstrated below.

break
The break statement is used to immediately stop a loop even if the condition has not been met.


It is effective when I find what I want and no longer need to continue.

Another example of the use of while loop and break statement

continue
The continue statement skips the current iteration and moves on to the next.

enumarate
Sometimes when looping, we need the item itself and the position at the same time. Indexes normally start at 0, but that would not make sense for positions, so we assign a starting point as demonstrated below.

nested loops
This is a loop inside a loop, and for every one round of the outer loop, the inner loop runs from start to finish.

Conclusion
Loops are important in Python as they automate operations.

Top comments (0)