While Loop in Python

This Blog Explains about Python While Loop and example programs

While Loop :-

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

Syntax:-

The syntax of a while loop in Python programming language is

while expression:

statement(s)

*While loop, test expression is checked first.

*The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.

*In Python, the body of the while loop is determined through indentation.

*The body starts with indentation and the first unindented line marks the end.

*Python interprets any non-zero value as True. None and 0 are interpreted as False.

*While expression end with Colon (:).

Example while loop Programs:

1. Print upto Given Number

begin_num=1

end_num=int(input(“Enter the number to print :”))

while end_num >= begin_num:

print(begin_num)

begin_num =begin_num+1

OUTPUT :-

Enter the number to print:6

1

2

3

4

5

6

>>>

2. Print the Reverse Number :-

last_num = int(input(“please enter the last number to print up to: “)

while last_num >= 0:

print (last_num)

last_num=last_num-1

Output:-

please enter the last number to print up to: 5

5

4

3

2

1

>>>>

3. Print the Odd number in Python :-

start_num= 1

end_num = int(input(“Enter the Last Number : ” ))

while start_num<= end_num:

print(start_num)

start_num+= 2

Output:-

Enter the Last Number : 10

1

3

5

7

9

>>>>>

Reference :

https://www.geeksforgeeks.org/python-while-loops/

https://www.programiz.com/python-programming/