Python while Loop
In Python, a while
loop is used to repeatedly execute a block of code as long as a certain condition is true. The basic syntax of a while
loop in Python is:
while condition: # execute this block of code as long as the condition is true
Here, condition
is any expression that can be evaluated to True
or False
. The block of code inside the while
loop is executed repeatedly as long as the condition
is True
. When the condition
becomes False
, the program moves on to the next statement after the while
loop.
For example, here's a simple while
loop that counts from 1 to 5 and prints each number:
i = 1 while i <= 5: print(i) i += 1
Output:
1 2 3 4 5
In this example, the while
loop executes as long as the value of i
is less than or equal to 5. The value of i
is initially set to 1, and each time through the loop, the value of i
is incremented by 1. The loop continues until the value of i
is greater than 5.
You should be careful when using a while
loop to avoid infinite loops. An infinite loop is a loop that never terminates because the condition is always True
. Here's an example of an infinite loop:
while True: print("Hello, world!")
This loop will continue to print "Hello, world!" indefinitely because the condition True
is always true. To stop an infinite loop, you can use Ctrl-C
to interrupt the program.
You can also use the break
statement to exit a loop prematurely if a certain condition is met. Here's an example:
i = 1 while i <= 5: if i == 3: break print(i) i += 1
Output:
1 2
In this example, the while
loop executes as long as the value of i
is less than or equal to 5, but when the value of i
is equal to 3, the break
statement is executed, and the loop is exited prematurely. As a result, only the values of i
less than 3 are printed to the console.