Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

While loop

while

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. Here’s the basic syntax:

While structure

Syntax while condition: # code to execute while condition is True
In this structure, condition is an expression that Python evaluates as either True or False. If the condition is True, the code block under the while statement (indented code) is executed. This process repeats until the condition becomes False. Here’s an example:

Simple example

Python basic while loop example count = 0 while count < 5: print(count) count += 1 # equivalent to 'count = count + 1'

Output

0 1 2 3 4
In this example, the condition is count < 5. Python checks whether count is less than 5. If it is, it prints the count and then increments count by 1. This process repeats until count is no longer less than 5.
The while loop can be controlled using break and continue statements. break is used to exit the loop prematurely and continue is used to skip the current iteration and proceed to the next one.

Here’s an example using break and continue:

While loop example using break,continue in python count = 0 while count < 5: if count == 3: break if count == 2: count += 1 continue print(count) count += 1

Output

0 1
In this example, when count is 3, the break statement is executed and the loop is terminated. When count is 2, the continue statement is executed and the rest of the loop for that iteration is skipped. Therefore, 2 is not printed. Let’s see jump statements like break, continue and pass in detail in upcoming topics!.

  📌TAGS

★python ★ loop ★ while

Tutorials