While-loops
As for loops, while loops are repeating structures which enable the execution of certain code blocks for multiple times. The difference is that for while loops the number of necessary repetitions is not known at the starting time of the loop.
While loops are executed until a termination condition is reached. In the following example, this condition is given by a > b
:
a = 7
b = 10
while a <= b:
print(a)
a += 1
# Output:
# 7
# 8
# 9
# 10
Obviously, this condition is executed 4 times (i.e. a = 7, 8, 9, 10). After that a + 1
gives 11 which is larger than b and the termination condition is reached.
As for any other loop, nested loops are also possible.
a = 7
b = 10
c = 10
while a <= b:
print(f"Outer loop value of a: {a}")
while c > a:
print(f" Inner loop value of c: {c}")
c -= 1
c = 10
a += 1
# Output:
# Outer loop value of a: 7
# Inner loop value of c: 10
# Inner loop value of c: 9
# Inner loop value of c: 8
# Outer loop value of a: 8
# Inner loop value of c: 10
# Inner loop value of c: 9
# Outer loop value of a: 9
# Inner loop value of c: 10
# Outer loop value of a: 10
Variable c
has to be reset to its initial value every time the inner loop is completed. Otherwise it would not start a second time since the termination condition is already reached. Of course this behavior can also be useful for a variety of problems.