Python while Loop

Here, we have discussed about python while loop with example and we will also learn about while loop with else. In Python, while loop is used to...

Hey folks! Welcome back to another interesting article on Python Programming Language

Python while loop

Here, we will discuss about python while loop with example and we will also learn about while loop with else.

What is Python while loop?

In Python, while loop is used to execute a given block of code or statement as long as the given condition is satisfied. And if the condition is not satisfied, then the next statement after the loop will be executed. Generally, the while loop is used when the number of iterations are not definite. In python, all non-zero values are interpreted as true and it will interpret None and 0 as false.

Syntax

while expression:
    statement(s)

Python while loop flowchart

Python while loop flowchart

Simple python while loop example;

i = 2

while i < 9:

  print(i)

  i += 2

Output

2

4

6

8

Example of python while loop using break statement;

i = 2

while i < 9:

  print(i)

  if (i == 4):

    break

  i += 2

Output

2
4

Example of python while loop using continue statement;

i = 1

while i < 9:

  i += 2

  if i == 4:

    continue

  print(i)

Output

3

5

7

9

While Loop with else

As we know that if the condition is not satisfied, then the next statement after the loop will be executed. But the programmers also has the option of adding else block. Similar to for loop, when the condition is not satisfied or is false then the part of else will be executed.

Syntax

while expression:

   statement(s)

else:

   statement(s)

Let's understand While loop with else  with the following illustration;

i = 1

while i < 9:

  print(i)

  i += 2

else:

  print("i is no longer less than 9")

Output

1

3

5

7

i is no longer less than 9

Conclusion

Above we have discussed about python while loop with example and we will also learn about while loop with else. In Python, while loop is used to execute a given block of code or statement as long as the given condition is satisfied.