Table of Contents
Python language while loop with example
In this tutorial, we will discuss the concept of the Python language while loop with example.
While loop in python
A while loop in python programming language repeatedly executes until a target statement is met and until given boolean condition is true.
Syntax of while loop
The syntax of while loop in the python programming language is given below.
Flow diagram of while loop
Example
1. Print Positive integer number less than ten using while loop in python
When the above code was executed, it produced the following output
1
2
3
4
5
6
7
8
9
10
Output
(10, 100)
(11, 105)
(12, 110)
(13, 115)
(14, 120)
(15, 125)
(16, 130)
(17, 135)
(18, 140)
(19, 145)
(20, 150)
(21, 155)
(22, 160)
(23, 165)
(24, 170)
(25, 175)
(26, 180)
(27, 185)
(28, 190)
(29, 195)
(30, 200)
(31, 205)
(32, 210)
(33, 215)
(34, 220)
(35, 225)
(36, 230)
(37, 235)
(38, 240)
(39, 245)
(40, 250)
End of the loop
2. Print first ten triangular number using whileloop in python
When the above code was executed , it produced the following output
0
1
3
6
10
15
21
28
36
45
3. print total number given input
When the above code was executed , it produced the following output
Enter any number for n6
(‘The total is’, 1)
(‘The total is’, 3)
(‘The total is’, 6)
(‘The total is’, 10)
(‘The total is’, 15)
(‘The total is’, 21)
Using else statement with while loop
Python accepts else statement associated with a while loop statement.
When the else statement is used with a whileloop in python, the else statement is invoked when the condition becomes false.
Program
when the above code was executed, it produced the following output
0 is less than or equal to 5
1 is less than or equal to 5
2 is less than or equal to 5
3 is less than or equal to 5
4 is less than or equal to 5
5 is less than or equal to 5
6 is not less than or equal to 5
Related post