SourceBae Blogs

Types of Loops in Python

In Python, there are two types of loops: for loops and while loops. A for loop is used to iterate over a sequence of elements, such as a list, tuple, or string. The basic structure of a for loop is as follows:

for variable in sequence: # code block to be executed

Here, sequence is any iterable object such as a list, tuple, or string and variable is a variable that takes on the value of each element in the sequence during each iteration of the loop. The code block inside the loop is executed for each element in the sequence.

Here is an example of a for loop that iterates over a list of numbers and prints each number:

numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)

A while loop, on the other hand, is used to execute a block of code repeatedly as long as a certain condition is true. The basic structure of a while loop is as follows:

while condition: # code block to be executed

Here, the condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed, and then the condition is evaluated again. If the condition is false, the loop is terminated.

Here is an example of a while loop that prints the numbers from 1 to 10:

count = 1 while count <= 10: print(count) count += 1

In addition to for and while loops, Python also has a few other types of loops such as:

  • for/else loop: the else block is executed only if the for loop completes all iterations without encountering a break statement.
  • while/else loop: the else block is executed only if the while loop completes all iterations without encountering a break statement.
  • break statement: which is used to exit a loop prematurely when a certain condition is met
  • continue statement: which is used to skip an iteration of a loop when a certain condition is met

Both for and while loops have their own unique use cases and it depends on the requirements and problem statement to decide which one to use.

In summary, a for loop is used to iterate over a sequence of elements, while a while loop is used to execute a block of code repeatedly as long as a certain condition is true. Python also provides other types of loops like for/else loop, while/else loop, break and continue statement for more advanced usage.

Share your love
Sourceblogs
Sourceblogs

India’s Leading Talent Marketplace For Remote Developers.

Leave a Reply

Your email address will not be published. Required fields are marked *