while
loops may be infinite, meaning they run forever unless there is a built in breaking condition or the user presses CTRL+C to terminate the script.
A breaking condition would be something like,
while (True):
if a_variable == some_value: break
where a_variable
may be changing state at some point in the iterations.
We typically see while loops written with a condition that must be met or the loop will terminate (or not start).
i = 10
while i > 0:
print (i)
i -= 1
As long a i
is greater than zero, the loop will continue to iterate. Once i
reaches 0
it will fail the condition.
continue
lets us skip execution of some or all of the code block if an internal condition exists. Say we have a list of numbers and one-word strings mixed in any order and we only want to print the strings…
We’ll use a for
loop since we know the list is finite and for loops have a definite duration, iterating over every value in the list then ending.
for x in a_list:
if not x.isalpha(): continue
print (x)
continue
lets us skip around the print()
statement.
Onto nested loops. When one loop is written in the code body of a loop it is said to be nested. The outer loop runs once through, but the inner loop runs through multiple times, since it runs on each iteration of the outer loop.
for i in range(1, 4):
for j in range(1, 11):
print (i * j)
The print statement will execute 30 times in the above example. The inner loop will run three times, and the outer loop will run once.
Comprehensions are essentially a list with a for loop inside that iterates an iterable and produces some result that is then stored within the list body. The result is a list of outcomes.
a = [x * 3 for x in range(1, 11)]
That will produce a list of numbers from 3 to 30, in threes.
[ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
Note how we produce the output with the expression in front of the for loop expression, and there is no colon or loop body.