while loops execute a set of statements as long as a condition is true.
i = 1 while i < 5: print(i)
This will print the data '1' without stopping as long as i is less than 5. Run the codes below.
We can stop this by adding a line of code to increase the value of i with each iteration.
i = 1 while i < 6: print(i) i += 1
With the break statement we can stop the loop even if the while condition is true.
i = 1 while i < 5: print(i) if i == 2: break i += 1
With the continue statement, we can skip over a part of the loop where an additional condition is set, and then go on to complete the rest of the loop.
i = 0 while i < 5: i += 1 if i == 2: continue print(i)
With the else statement, we can run a block of code once when the condition no longer is true.
i = 1 while i < 5: print(i) i += 1 else: print("i is no longer less than 5")
Assign the integer 10 to variable i and increase it by 10 for each iteration.
1. while loop - Print the iteration as long as it is below 100.
2. while loops with continue - Skip the iteration when it is at 50.
3. while loops with break - Stop the iteration at 70.
4. while loops with else - Once the iteration reaches 100, print "i is no longer less than 100".