while loop in python

The basic syntax for while loop in Python is as follows:

main.py
while condition:
    # code block
34 chars
3 lines

The loop will keep running until the condition is True. Once the condition becomes False the loop will terminate and the program will continue to execute whatever is after the loop.

For example, let's say we want to print numbers from 0 to 4 using while loop. We can write the following code to achieve that:

main.py
count = 0
while count < 5:
    print(count)
    count += 1
59 chars
5 lines

Output:

main.py
0
1
2
3
4
10 chars
6 lines

In the above example, the condition is count < 5 and we start with count = 0. We print the value of count and increment it by 1. This process is repeated until the condition becomes False.

Note: Be careful while using while loop, since if the condition is always True the loop will become an infinite loop and the program will never terminate. In that case, you'll need to manually terminate the program.

In general, the while loop is useful when you need to execute a block of code repeatedly until a certain condition is met.

related categories

gistlibby LogSnag