Python Loops


Python has two types of loops: while loops and for loops. While loops execute a block of code repeatedly as long as a specified condition is true.

The syntax for a while loop is:

The condition is evaluated before each iteration of the loop. If the condition is true, the code block is executed. If the condition is false, the loop terminates. For example, the following code prints the numbers from 1 to 5:


For loops iterate over a sequence of values.

The syntax for a for loop is:

The sequence can be a list, a tuple, a string, or any other iterable object. The variable is assigned each value in the sequence, and the code block is executed once for each value.

For example, the following code prints the elements of the list [1, 2, 3, 4, 5]:



Both while loops and for loops can be used to execute code repeatedly. The choice of which type of loop to use depends on the specific situation.

While loops are generally used when the number of iterations is not known in advance, while for loops are generally used when the number of iterations is known.

Here are some additional things to keep in mind about loops in Python:

The else clause: A for loop or while loop can have an else clause. The else clause is executed when the loop terminates normally (i.e., not because of a break or return statement).

The break statement

The break statement terminates the current loop.

The continue statement

The continue statement skips the rest of the current loop iteration and goes to the next iteration.

Here are some examples of how to use the break and continue statements in Python:


As you can see, the break statement terminates the loop immediately, while the continue statement skips the rest of the current iteration of the loop.

Here are some other things to keep in mind about the break and continue statements:

The break statement can be used with both while loops and for loops. The continue statement can only be used with for loops. The break and continue statements can be used anywhere inside a loop body, but they must be followed by a semicolon (;).

Enroll Now

  • Python Programming
  • Machine Learning