How do I use loops in Python

In Python, loops are used to iterate over a sequence (like a list, tuple, or string) or to repeat a block of code multiple times.

The two main types of loops in Python are:

  • for loop: Used for iterating over a sequence (like a list or string).
  • while loop: Repeats as long as a certain condition is true.

Here’s an example of how to use both loop types in Python:

# For loop example fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit) # While loop example count = 0 while count < 5: print(count) count += 1

Python loops for loop while loop iterate programming