DEV Community

Cover image for Understanding for loop in Python
EzeanaMichael
EzeanaMichael

Posted on

Understanding for loop in Python

The for..loop is also a type of iteration or iterating sequence, which repeats a certain block of code at certain times until a certain condition is reached.
The loop can be used to iterate over a fixed number of times
Code:
Image description
Output:

Image description

For number in range(9)
Where 9 is the number of times from 0 to 9
In the range function, you can specify the starting point and the ending point of the loop, as well as the number of steps to jump that, is range(start, stop, skip)
See the three different codes and what is displayed by them.
Code:

Image description
Output:

Image description

The for loop unlike the while loop can be used to iterate over lists
This is done by the following blocks of code
Following the structure
For (the name assigned to all values in the list) in (name of the list):
Then certain operations can be performed
Play around with the code and see what you can come up with.
Code:
Image description
Output:

Image description

Here's an example of the same code I wrote with while loop last week wrote with for loop
Code:

Image description
Output:

Image description
The difference between the for loop and the while loop in python is the application
The while loop can be used to run conditions a certain number of times even when the number of times is unknown.

The for loop can only be used to iterate over a fixed number of times provided I'm the range()

The while loop cannot be used to iterate over a list
The for loop is used to iterate over the list

I generally use the while loop for an unknown number of times which can be input by the user when the code run over for the loop
I use For loop when dealing with lists

Hope you enjoyed this short lesson
From the next lesson, we'll start using our current knowledge to solve some programming problems,
Read, like, share, and have a wonderful day

Top comments (2)

Collapse
 
sojinsamuel profile image
Sojin Samuel

Bravo Mikey

Collapse
 
ezeanamichael profile image
EzeanaMichael

Thanks😇