Python loop


loops

Loops can repeat some specific section of the code as many times as needed by the user.

Why do we prefer using loops in python?

It enables changing the program’s flow so that instead of writing the exact same section code repeatedly and eventually hampering the time complexity, we can repeat the same code for a finite number of times using the loops.

Advantages of loops

  • It provides re-usability of the section code.
  • Using loops, we do not need to write the same section of code repeated several times.
  • Using loops, we can traverse over all the elements of data structures present in the code.

In the Python programming language, two primitive loop commands exist:

  • While loops
  • for loops

While loops in Python:

It is probably the first loop you will discover when you start learning how to program. The word "while" has got to do something with "interval" or a "period." The "while" executes a piece of code repeatedly as long as the condition goes true.

  • It is written using a while keyword.
  • A set of statements that must be repeatedly executed.
  • The condition either evaluates to True or False.

break Statement:

Using a break statement, you can terminate a loop even if the while condition implies true

For Loops in Python:

The "for" loop is being utilized for repeating over a sequence (it can be either a list, a tuple, a dictionary, a set, or even a string). It is just like a keyword in different programming languages and runs more like an iterative method observed in different object-orientated programming languages. Using a for loop, you can run a piece of code once for every item in a list, tuple, set, etc.