Loops In Python
Python Loops: For and While
Python has two primitive loop commands: while loops and for loops.
With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i < 6:
print(i)
i += 1
[!NOTE] Remember to increment
i, or else the loop will continue forever!
With the break statement we can stop the loop even if the while condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
To loop through a set of code a specified number of times, we can use the range() function.
| Function | Result |
| :--- | :--- |
| range(6) | Values from 0 to 5 |
| range(2, 6) | Values from 2 to 5 |
| range(2, 30, 3) | Values from 2 to 29, incrementing by 3 |
for x in range(2, 6):
print(x)
The else keyword in a for or while loop specifies a block of code to be executed when the loop is finished.
for x in range(6):
print(x)
else:
print("Finally finished!")
[!IMPORTANT] The
elseblock will not be executed if the loop is stopped by abreakstatement.
4. Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass