Python Loops

What Are Loops?

Loops allow you to repeat a block of code multiple times without rewriting it. This makes your program more efficient and scalable. For example, if you want to print all items in a list or keep checking user input until it's valid, loops are the perfect tool.

Python has two main types of loops:

  1. for loops, which iterate over sequence
  2. while loops, which repeat while a condition is true.

for Loops

The for loop in Python is used to iterate over a sequence like a list, string, or range of numbers. Each iteration allows you to perform actions on the current item.

Basic Structure

for item in sequence:
      # do something

The variable after for (like i or name) changes each time through the loop. It takes on each value from the sequence.

Example 1

Loading...
Output:

Example 2

Loading...
Output:

while Loops

The while loop continues to run as long as its condition remains true. It's useful when the number of iterations isn't predetermined, like reading input until a user enters "quit".

Basic Structure

A while loop is used to repeat a block of code as long as a given condition is True. It’s useful when the number of repetitions isn’t known ahead of time.

The loop checks the condition before each iteration. If the condition becomes False, the loop stops.

while condition:
      # code to repeat
Loading...
Output:

break and continue

break lets you exit a loop early when a condition is met.continue skips the current loop iteration and proceeds to the next one.

Example 1

Loading...
Output:

Example 2

Loading...
Output:

Nested Loops

A nested loop is a loop placed inside another loop. In Python, you can nest for loops, while loops, or a combination of both.

The inner loop runs completely every time the outer loop runs once. Nested loops are useful for working with grids, matrices, or repeated patterns.

Loading...
Output:

This example prints all combinations of i and j from 1 to 3.

Practice Prompt

Write a for loop that prints each letter in the string "Python" on its own line.

Expected Output:

P
y
t
h
o
n
Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic