Skip to main content

2. Loops

Loops repeat code. Python has two loops:
  • for
  • while

for Loop

Used for iterating over sequences.

Syntax


Loop through List

Output

Loop through String


Using range()

range(stop)

Output

range(start, stop)

Output

range(start, stop, step)

Output

Nested Loops


Loop through Dictionary


Loop Control Statements

break

Stops the loop immediately.
Output

continue

Skips current iteration.
Output

pass

Placeholder.

else with Loop

Runs only if loop finishes normally.
Output

while Loop

Repeats while condition is True.

Syntax


Example

Output

Infinite Loop

Stop using Ctrl + C.

break in while


continue in while


Quick Revision

Loops

  • for → Iterate over sequences.
  • while → Repeat while condition is True.
  • break → Exit loop.
  • continue → Skip current iteration.
  • pass → Placeholder.
  • Loop else → Executes if loop completes normally.