In programming, loops are used to repeat a block of code. For example, if we want to show a message 100 times, then we can use a loop. It's just a simple example, we can achieve much more with loops. Show In the previous tutorial, we learned about Python for loop. Here, we are going to learn about 0 loops.Python 0 loop is used to run a specific code until a certain condition is met.The syntax of 0 loop is:
Here,
Flowchart for Python While LoopFlowchart for while Loop in PythonExample: Python while Loop
Output 1 2 3 4 5 Here's how the program works: VariableCondition: 1 2 3 4 52Action 1 2 3 4 53 1 2 3 4 54 61 2 3 4 56 is printed. 1 2 3 4 57 is increased to 2. 1 2 3 4 58 1 2 3 4 54 6 1 is printed. 1 2 3 4 57 is increased to 3. 31 2 3 4 54 6 6 is printed. 1 2 3 4 57 is increased to 4. 81 2 3 4 54 6You have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends1 is printed. 1 2 3 4 57 is increased to 5. You have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends3 1 2 3 4 54 6You have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends6 is printed. 1 2 3 4 57 is increased to 6. You have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends8 1 2 3 4 54 9The loop is terminated.Example 2: Python while Loop to Display Game Level
Output You have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends In the above example, we have used the 0 loop to check the current level and display it on the console.Infinite while Loop in PythonIf the 4 of a loop is always 6, the loop runs for infinite times (until the memory is full). For example,
In the above example, the 4 is always 6. Hence, the loop body will run for infinite times.Python While loop with elseA 0 loop can have an optional 7 block as well.The 7 part is executed after the 4 in the while loop evaluates to 9. For example,
Output Inside loop Inside loop Inside loop Inside else Here, we have used the counter variable to print the 1 string three times.On the fourth iteration, the condition in 0 becomes 9. Hence, the 7 part is executed. |