PieceOfAPie
PieceOfAPie
  • Home
  • Tutorials
  • More
    • Home
    • Tutorials
  • Home
  • Tutorials

While Loops

Previous Lesson


Last lesson, we learned about for loops. But imagine if you want that for loop to run forever. That is called a while loop. A while loop is a loop that runs until a condition is true. If there is no condition, then it will run forever. Here is an example:

  •  No Condition


There are two ways to stop a while loop. You can use a condition, or you can use a break in the middle of the loop. A break is any point in the while loop in which you can stop the while loop and move onto the next line. You can also write breaks in any loop including for loops. Below are examples of breaks and conditions.

  • Condition
  • Break 


If you want a while loop that goes on forever instead, you can just put True as the condition.

You can write a while loop like this.

while condition:

    [What you want to put in the while loop]

While Loops Exercise

Make a program that repeats a question to the user using while loops and breaks the loop when the user gets the question right. 

Next Lesson

Functions

Copyright © 2024 PieceOfAPie - All Rights Reserved.

Powered by GoDaddy

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept