Loops are how programs do repetitive work without repeating code. Python gives you two fundamental loop constructs: theDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/marioaje/Python/llms.txt
Use this file to discover all available pages before exploring further.
for loop, which iterates over a sequence a known number of times, and the while loop, which keeps running as long as a condition remains True. Understanding when to use each — and how to control them — is essential for writing efficient Python programs.
for Loop with range()
The for loop is Python’s counting loop. When paired with the built-in range() function it runs a block of code a precise number of times, giving you access to the current counter value on every iteration.
range(start, stop, step)
| Argument | Meaning | Default |
|---|---|---|
start | First value produced (inclusive) | 0 |
stop | Upper bound (exclusive — never produced) | required |
step | How much to add each iteration | 1 |
Ascending counter
for.py
Descending counter
Pass a negative step to count backwards:for.py
contador is incremented twice per iteration (contador = contador + 1 and then contador += 1), so after 3 passes through the loop it reaches 6.
for-in Loop (foreach-style)
When you need to visit every element of a list (or any other iterable) without caring about the index, use the for item in collection: pattern. This is Python’s equivalent of a foreach loop in other languages.
foreach.py
mylista. The loop variable item takes on each value in order, one per iteration.
while Loop
A while loop runs its body repeatedly as long as its condition evaluates to True. Unlike for, you control the counter yourself — which makes while ideal when the number of iterations is not known in advance.
while.py
while that counts from a negative starting point all the way up to 333:
while.py
-100 to 333 inclusive — a total of 434 iterations — before condicion becomes 334 and the condition condicion <= 333 turns False, ending the loop.