Python Loops
Python has two primitive loop commands:
- while loop
- for loop
while loop
If we use a while loop, we can execute a set of statements as long as the condition is true.
an actual example
Prints i as long as i is less than 7:
i = 1 while i < 7: print(i) i += 1
running example
1 2 3 4 5 6
Note: Remember to increment i or the loop will continue forever.
The while loop needs to have the relevant variables ready. In this example, we need to define an index variable i, which we will set to 1.
break statement
If we use the break statement, we can stop the loop even if the while condition is true:
an actual example Exit the loop when i equals 3:
i = 1 while i < 7: print(i) if i == 3: break i += 1
running example
1 2 3
continue statement
If we use the continue statement, we can stop the current iteration and move on to the next one:
an actual example
If i equals 3, continue to the next iteration:
i = 0 while i < 7: i += 1 if i == 3: continue print(i)
running example
1 2 4 5 6 7
else statement
By using the else statement, we can run the block once when the condition no longer holds:
an actual example
Prints a message when the condition is false:
i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")
running example
1 2 3 4 5 i is no longer less than 6
To this point this tutorial on Python Getting Started (XVII) Python's While loop is introduced to this article, more related to Python's While loop content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!