DEV Community

Cover image for while loop
Python64
Python64

Posted on

while loop

Python While Loops

You can use the Python programming to create loops. The most common loops in programming are the for loop, do while loops and the while loop.

So one of those loops is the while statement for executing a program loop. Under certain conditions, the same task is repeated.

The basic form:

    while judgment conditions:
        Execute the statement ......

Execute statement may be a single statement or a block. The condition can be any expression. If the determination condition is false, the cycle ends.

If you are new to Python, you may like this Python course

Performing the following flow chart:

while loop

Example:

count = 0
while (count <9): 
    print('The count is:', count)
    count = count + 1 
print("Good bye!")

Above the output code execution:

    The count is: 0
    The count is: 1
    The count is: 2
    The count is: 3
    The count is: 4
    The count is: 5
    The count is: 6
    The count is: 7
    The count is: 8
    Good bye!

There are two important statements that can be used in loops:

  • break is used to exit the loop
  • continue to skip this cycle,
# Continue and break usage
    
i = 1
while i <10: 
    i += 1 
    if i%2 > 0:
       continue
       print(i) # 2,4,6,8,10 output bis

i = 1
while 1: # 1 cycling conditions must be established
    print(i)
    i += 1
    if i > 10: # 10 out of the loop when i is greater than
        break

Infinite loop

If the conditional statement is always true, infinite loop will execute it, the following example:

var = 1
while var == 1: # This condition is always true, an infinite loop will execute down
    num = input( "Enter a number:")
    print("You entered:", num)

print("Good bye!")

Examples of the above output:

    Enter a number: 20
    You entered: 20
    Enter a number: 29
    You entered: 29
    Enter a number: 3
    You entered: 3
    Enter a number between: Traceback (most recent call last):
      File "test.py", line 5, in <module>
        num = input ( "Enter a number:")
    KeyboardInterrupt

That's because you enter num, but var stays the same each cycle.

Note: The above infinite loop you can use CTRL + C to interrupt the cycle.

recycled else statement

In python, you can use while ... else, as the example below:

count = 0
while count <5:
    print(count, "is less than 5")
    count = count + 1
else:
    print(count, "is not less than 5")

Examples of the above output is:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

More reading:

Top comments (1)

Collapse
 
aartiyadav profile image
Aarti Yadav

Great information on while loop, Can you put some information for do while loop? I am reading this post for Python while loop. I hope you also like this hackr.io/blog/python-while-loop