Python while Loop :

The while Loop :

With the while loop we can execute a set of statements as long as a condition is true.

Example :

  1. i = 0
  2. print("While loop example:\n")
  3. while i < 8:
  4. print(i)
  5. i += 1
  6. input()

Output :

python while loop example

while loop with Statements :

With the break statement we can stop the loop even if the while condition is true and the continue statement we can stop the current iteration, and continue with the next.

Example 1 :

  1. x = 0
  2. while x < 8:
  3. print(x)
  4. if x == 4:
  5. break #Exit the loop when i is 4
  6. x += 1
  7. input()

Output 1 :

python while loop with break statement

Example 2 :

  1. y = 0
  2. while y < 8:
  3. y += 1
  4. if y == 4:
  5. continue #Continue to the next iteration if i is 4
  6. print(y)
  7. input()

Output 2 :

python while loop with continue statement

Nested while loops :

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

Example 1 :

  1. n = 10
  2. x = 10
  3. y = 0
  4. while x < 20:
  5. while y < n:
  6. print("\n",y,end="")
  7. y+=1
  8. print("\n",x,end="")
  9. x+=1
  10. input()

Output 1 :

python nested while loop example

Example 2 :

  1. n = 10
  2. x = 10
  3. y = 0
  4. while x < 20:
  5. while y < n:
  6. print("\n",x,"+",y,"=",x+y,end="")
  7. y+=1
  8. x+=1
  9. input()

Output 2 :

python nested while loop (sum) example

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes