Skip to main content

Python Tutorial 3.2 - Loops in Python

Welcome to the "Loops in Python" tutorial!


Overview

Loops allow you to iterate over sequences or execute a block of code repeatedly until a condition changes. Python provides two primary loop types: for loops and while loops.

For Loops

For loops iterate over a sequence (such as a list, tuple, or string).

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

While Loops

While loops execute as long as a condition is true.

Example:

count = 0
while count < 5:
    print("Count is:", count)
    count += 1

Key Takeaways

  • For Loops: Best for iterating over sequences.
  • While Loops: Use when the number of iterations is not predetermined.
  • Remember to prevent infinite loops by ensuring the loop condition will eventually be false.

Happy looping!

Comments