#14 While Cycle / Python Lessons for Beginners

by Alex
#14 While Cycle / Python Lessons for Beginners

Previous lesson: Conditional expressions and if Python has two simple loop commands:

  • while loop
  • the cycle for

While loop

With the while loop we can perform actions as long as the condition is true. Output i, as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1

Output:

1
2
3
4
5

Note: don’t forget to increase i, otherwise the loop lasts forever. For the while loop it is necessary that the appropriate variables are declared, in this example we need to declare the indexing variable i, which we set to 1.

Break the loop

With the break statement, we can stop the loop even if the while condition is true: Exit the loop when it equals 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

Output:

1
2
3

Operator continue

With the continue operator we can stop the current iteration and go on to the next one: Continue until the next iteration until i equals 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Conclusion:

1
2
4
5
6

Related Posts

LEAVE A COMMENT