Without loops, almost any programming task would become impossibly tedious. Loops are a fundamental control structure that allows you to execute a block of code repeatedly. They encapsulate what computers do best: repetition and iteration. Instead of writing the same code over and over, you can write it once inside a loop.
Table of Contents
💻 The `for` Loop
The `for` loop is one of the most common loop types. It is designed to iterate over a sequence of items, such as a list or a range of numbers. In Python, a typical `for` loop looks like this:
# This loop will run 5 times, with i taking values 0, 1, 2, 3, 4
for i in range(5):
print(i)
The range(5)
function generates a sequence of numbers from 0 up to (but not including) 5. The loop assigns each number in this sequence to the variable `i`, one at a time, and executes the indented code block for each.
💻 The `while` Loop
The `while` loop is more primitive but also more flexible. It simply repeats a block of code as long as a given condition is true. It doesn’t handle the iteration variable for you; you have to manage it yourself.
i = 0
while i < 5:
print(i)
i = i + 1 # You must increment the counter yourself!
The `while` loop is perfect for situations where you don’t know in advance how many times you need to loop. For example, you could loop `while user_input != ‘quit’` to keep a program running until the user decides to exit. Be careful not to create an infinite loop where the condition never becomes false!
💻 Breaking and Continuing
Sometimes you need to alter the flow of a loop. Most languages provide keywords for this:
- The
break
statement exits the loop immediately, regardless of the loop’s condition. - The
continue
statement skips the rest of the current iteration and jumps to the beginning of the next one.
These tools give you fine-grained control over how your loops execute.
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes