What are While loops in Python?
With the while loop, we can execute a set of statements as long as a condition is true.
Syntax
while condition:
return statement
increment/decrement
The while loop requires relevant variables to be ready, in this example, we need to define an indexing variable, i, which we set to 1.
Example:
Print i as long as i is less than 6
i = 1
while i < 8:
print(i)
i += 1
#1
#2
#3
#4
#5
#6
#7
Break Statement
The Break Statement can help to stop the loop even if the condition is true
Syntax
while condition:
return statement
if condition:
break
increment/decrement
Example
i = 1
while i < 8:
print(i)
if i == 3:
break
i += 1
#1
#2
#3
Continue Statement
Unlike the break statement, the continue statement will stop only the current iteration and continues with the next iteration.
Syntax
while condition:
return statement
if condition:
continue
increment/decrement
Example
i = 0
while i < 8:
i += 1
if i == 3:
continue
print(i)
#1
#2
#4
#5
#6
#7
#8
ย