Python While Loops

Iterative Statements

If you want to execute a group of statements multiple times then you should go for iterative statements.

Python supports 2 types of iterative statements.

  • while loop
  • for loop

While loop

If you want to execute a group of statements iteratively until some condition false, then you should go for while loop.

The syntax of while loop in Python programming language as follows,

while expressions:
    statements

You can print numbers from 1 to 10 by using while loop as follows.

x=1
while x <=10:
    print(x)
    x=x+1

Output

1
2
3
4
5
6
7
8
9
10

Eg: To display the sum of first n numbers,

n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
    sum=sum+i
    i=i+1
    print("The sum of first",n,"numbers is :",sum)

Output

Enter number:5
The sum of first 5 numbers is : 1
The sum of first 5 numbers is : 3
The sum of first 5 numbers is : 6
The sum of first 5 numbers is : 10
The sum of first 5 numbers is : 15

Else Statement

Using else statement you can run a block of code once when the condition no longer is true,

i = 1
while i < 5:
    print(i)
    i += 1
else:
    print("i is no longer less than 5")

Output

1
2
3
4
i is no longer less than 5

Break Statement

Using break statement you can stop the loop even if the while condition is true,

i = 1
while i < 5:
    print(i)
    if i == 2:
      break
    i += 1

Output

1
2

Continue Statement

Using continue statement you can stop the current iteration, and continue with the next,

i = 0
while i < 5:
    i += 1
    if i == 2:
      continue
    print(i)

Output

1
3
4
5

Read Also : Python – Decision Making ( IF ELSE Statement )

Share on:

Ravindra Kumar

Hi, This is Ravindra. I am founder of TheCodeCloud. I am AWS Certified Solutions Architect Associate & Certified in Oracle Cloud as well. I am DevOps and Data Science Enthusiast.

Leave a Comment