Loops Cheatsheet

Complete Python Loops cheatsheet with clear examples for quick revision

WHAT IS A LOOP?

A loop is used to repeat a block of code multiple times until a condition is met. Instead of writing the same code again and again, we use loops.

Real-life examples:

  • Asking attendance of 50 students one by one

  • Printing numbers from 1 to 10

Why do we need loops?

  • To save time

  • To reduce code repetition

  • To work with lists, strings, and ranges

  • To automate repetitive tasks

Types of loops in Python

  • while loop

  • for loop


while Loop

Definition A while loop is used when we do not know how many times the loop will run. It runs as long as a condition is true.

Syntax

1

Example: Factorial using while loop

2

Example: Print numbers from 1 to 5

3

Example: Print each character of a string using while loop

4

Example: Print each word in a sentence using while loop


for Loop

Definition A for loop is used when we know in advance how many times the loop should run.

Syntax

1

Example: Print numbers from 1 to 5

Note: range(1, 6) means numbers from 1 to 5 (6 is excluded).

2

Example: Print each character of a string

3

Example: Loop through a list

Common use of range()

  • range(5) → 0 to 4

  • range(1, 5) → 1 to 4

  • range(1, 10, 2) → 1, 3, 5, 7, 9

Iterating using range()

Definition

range() is used to generate a sequence of numbers. It is commonly used with for loops when we want to repeat something a fixed number of times.

Syntax

  • start → starting number (default: 0)

  • stop → ending number (not included)

  • step → gap between numbers (default: 1)

Examples:


Iterating using enumerate()

Definition

enumerate() is used when we want both the index and the value while looping through a sequence (list, string, etc.).

Syntax

Examples:


Infinite Loop

If the condition never becomes false, the loop runs forever.


Loop Control Statements

These statements control the flow of loops.

1

break

Definition : break is used to stop the loop immediately.

2

continue

Definition : continue is used to skip the current iteration and move to the next one.

3

pass

Definition : pass is used when we don’t want to write code yet, but need the loop syntax.


Nested Loops (Loop inside Loop)

Definition : A loop inside another loop is called a nested loop.

1

Example 1

2

Example 2

Last updated