Categories: PythonWhile statement

Python language while loop with example

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

 
Flow diagram


Example

1. Print Positive integer number less than ten using while loop in python
Example

When the above code was executed, it produced the following output

1
2
3
4
5
6
7
8
9
10

 

Example
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
Example
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

Karmehavannan

Recent Posts

Multiply two numbers in Java using scanner| 5 different ways

Multiply two numbers in Java using scanner| 5 different ways In this article, we will…

3 months ago

5 different ways to Divide two numbers in Java using scanner

5 Different ways to Divide two numbers in Java using scanner In this article, we…

3 months ago

Learn 8 Ways to Subtract Two Numbers Using Methods in Java

Learn 8 Ways to Subtract Two Numbers Using Methods in Java In this article, we…

4 months ago

10 ways to subtract two numbers in Java

10 ways to subtract two numbers in Java In this article, we will discuss the…

4 months ago

Java Code Examples – Multiply Two Numbers in 5 Easy Ways

Java Code Examples – Multiply Two Numbers in 5 Easy Ways In this article, we…

4 months ago

How to Divide two numbers in Java| 5 different ways

How to Divide two numbers in Java| 5 different ways In this article, we will…

4 months ago

This website uses cookies.