How To Loop A Program In Python

In this tutorial, we will discuss how to loop a program in Python. Loops are an essential programming construct used to execute a block of code repeatedly for a specified number of times or until a certain condition is met.

Python provides two main types of loops: for loops and while loops. We will go through each type and learn how to implement them effectively in a Python program.

For Loop

A for loop is used for iterating over a sequence (e.g., a list, tuple, or a string). It is designed in such a way that it executes the block of code for each item in the sequence:

Let’s see an example using for loop to iterate through a list of numbers:

  1. Create a list of numbers:
  1. Use a for loop to iterate through the list:

Output:

1
2
3
4
5

While Loop

A while loop is used to repeatedly execute a block of code as long as a specified condition is True. If the condition is not met or becomes False, the loop terminates:

Here’s an example using while loop to print the numbers from 1 to 5:

  1. Initialize a variable as a counter:
  1. Use a while loop to iterate as long as the counter is less than or equal to 5:

Output:

1
2
3
4
5

Break and Continue Statements

Python offers additional control over loops with the break and continue statements.

Break statement: It is used to terminate the loop when a certain condition is met. Here is an example of using a break statement inside a for loop:

Output:

1
2
3

In the above example, the loop terminates when the value of num becomes 4.

Continue statement: It is used to skip the rest of the block and jump to the next iteration of the loop. Here is an example using a continue statement inside a for loop:

Output:

1
2
3
5

In this example, when the value of num becomes 4, the loop skips the print statement and moves to the next iteration.

Full Code

Conclusion

In this tutorial, we covered how to use for loops and while loops in Python, as well as the usage of break and continue statements for controlling the flow of iteration. Understanding and mastering loops are vital in creating efficient and effective Python programs.