HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Loops (for / while)

Loops (for / while)

Iterating over sequences with for, generating numbers with range, conditional repetition with while, break and continue.

Simple enough for a 5-year-old to understand

for and range

for loops over each element of a sequence. range() generates a given number of repetitions.

Example code
1
for i in range(1, 4):
Loops through 1, 2, 3 (4 is NOT included).
LoopLoops through 1, 2, 3 (4 is NOT included).
2
print(i)
Writes each number: 1, 2, 3.
Output / InputWrites each number: 1, 2, 3.
LoopOutput / Input
💡 Hint: range(n) → 0 to n-1. range(1, 4) → 1,2,3. The end is always excluded.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

A loop is a way to do the same task over and over again. Processing a thousand-line file, summing the price of every item in a list, or trying an operation until it succeeds—all of this is done with loops. Writing code without loops means manually copying the same line a hundred times.

There are two types of loops in Python, and when to use which is clear. If you know how many times it will run or want to iterate over the elements of a collection, you use for. If you don't know how many times it will run and want to continue until a condition is met, you use while.

What you will learn

  • iterating over lists and strings with for
  • generating a specific number of repetitions with range
  • setting up conditional repetition with while
  • breaking out of a loop with break, and skipping an iteration with continue
  • getting both the index and value together with enumerate
  • generating table-like structures with nested loops

When to use?

You use a for loop when processing the lines of a file, handling records in an API response one by one, or calculating a total or average from a list.

You use a while loop for tasks with an unknown number of endings, such as asking for input until the user provides a valid one, retrying a connection until it succeeds, or processing a queue until it is empty.

Common mistakes

Wrong

i = 0
while i < 5:
    print(i)

Because the loop variable never increments, the condition remains true forever and the program runs infinitely. Infinite loops are the most common mistake when using while; make sure you modify the variable inside the loop.

Correct

i = 0
while i < 5:
    print(i)
    i += 1

Wrong

for i in range(1, 5):
    print(i)

range excludes the end value: this code prints 1, 2, 3, 4, not 5. If you want from 1 to 5 including 5, you must give the end as 6. This is the most common reason for the output being short by one.

Correct

for i in range(1, 6):
    print(i)

Wrong

for i in range(len(items)):
    print(items[i])

It technically works, but it is unnecessary in Python and prone to errors. Iterating directly over elements is shorter and safer; if you also need the index, use enumerate.

Correct

for item in items:
    print(item)

Frequently asked questions

Should I use for or while?

Rule of thumb: use for if the number of repetitions or the collection you are iterating over is known, and while if the end depends on a condition. In Python, the for loop is used much more frequently because lists, dictionaries, and files can be iterated over directly.

What is the difference between break and continue?

break completely terminates the loop and moves on to the line after the loop. continue only interrupts that single iteration, and the loop continues with the next element. Use break when you find what you are looking for, and continue for records to be skipped.

I'm stuck in an infinite loop, how do I exit?

The Ctrl and C key combination stops a program running in the terminal. Afterwards, check the loop condition and make sure the variable inside actually changes. For safety, it is also a common practice to put a maximum iteration limit on while loops.

Summary

for is used for collections and specific repetition counts, while is used for conditional repetition; break and continue manage the flow. The two most common mistakes: forgetting to increment the variable inside a while loop and overlooking that range is exclusive of the end.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code