Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Intermediate Concepts in Python: Conditions and Iteration

This guide was created for those interested in increasing their Python programming knowledge. This guide is best for those who have some familiarity with basic concepts in Python.

What are WHILE statements?

WHILE statements (also known as WHILE loops) are used to control the flow of a process. WHILE statements employ the keywords "continue" and "break" to help control the procession flow.


In this section, you will learn how to:

  • Employ WHILE statements using "continue" or "break" (WHILE Statements)

WHILE Code Examples

Copy the following code on the left in your IDE to execute the process shown in the image on the right.


While Loop

In this example, the while loop is complete when the variable (x) reaches 6. This is shown in the "Final output"  statement.

x = 0                                                  Jupyter Notebook View
while x < 6:
    x+=2 
    print("Looping output:", x)


print("Final output:", x)

 

 


While Loop with Break

In this example, the WHILE loop has been updated to run until x reaches 12 while the IF statement breaks the loop at 6. Due to this, the loop will not reach 12 and the final output will be 6

x = 0                                              Jupyter Notebook View

while x < 12:
    x+=2 
    if x == 6:
        break  
    print("Looping output:", x)

 

 

 

 

 


While Loop with Continue

In this example, continue is used to interrupt the loop when x becomes 6. Therefore, 6 will not be printed as a "Looping output:".

x = 0                                         Jupyter Notebook View

while x < 12:
    x+=
    if x == 6:
        continue 
    print("Looping output:", x)

print("Final output:", x)

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.