Python Programming - The While Statement

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – The While Statement

The while loop is used to repeat a set of statements as long as the condition is true. In Python, an indefinite loop is implemented using the while statement. The indefinite loop keeps iterating until certain conditions are met. The syntax of the while statement is as follows:

while (<condition>):
<body>

Here, the condition is a Boolean expression. The body of the loop executes repeatedly as long as the condition is true. When the condition becomes false, the loop terminates.

Python Programming - The While Statement chapter 5 img 1

Note that the condition is always tested first before the loop body is executed. This kind of structure is called a pre-test loop. If the loop condition is initially false, the loop body will not execute at all. Here is an example of a simple while loop that counts from 0 to 10:
i = 0
while (i <= 10):
print(i)
i = i + 1

The above-mentioned program will produce numbers from 1 to 10 as an output. Here the repetitive block after the while statement involves incrementing the value of an integer variable and printing it. Before the block begins, the variable i is initialized to 0. Till it is less than equal to 10, i is incremented by 1 and printed to display the sequence of numbers.

Figure 5.23 shows the flow of control for the while statement. As long as x is less than y, the program continues to execute the while loop. With each pass through the loop, x is incremented by one. When it is no longer less than y, control comes out of the loop and flows to the next statement.

Let’s Try

num = 0
while (num< 10):
num = num + 1
print(“num =”, num)

Simple Programs

Example 17.
Program to display the string “Hello World” five times.

Figure 5.24 shows the program displaying the string “Hello World” five times using the while loop.

# Demonstration of while loop
count = 0
while(count <=4):
print(“Hello World”)
count= count + 1
print (“Done”)RUN
>>>
Hello World
Hello World
Hello World
Hello World
Hello World
Done
>>>

Example 18.
Program to display gross pay of three employees using while loop The program segment shown in Figure 5.25 computes and displays gross pay of three employees. The looP body sets an employee’s payroll data and computes and displays pay. After gross pay of each pay for three employees using while loop. the employee is displayed, “All employees processed” message will be displayed at last.

# Program to display gross pay of three employees using while loop
count_emp = 0
while(count_emp <3):
hours = int (input (“Hours :11))
rate = float(input(“Rate :”))
pay = hours * rate
print(“Pay is Rs. “, pay)
count_emp = count_emp +1
print( “All employees processed” )RUN
>>>
Hours :2
Rate :200
Pay is Rs. 400.0
Hours :4
Rate :500.25
Pay is Rs. 2001.0
Hours :8
Rate :750.75
Pay is Rs. 6006.0
All employees processed
>>>

Let’s Try

What is the output of following code fragments?

count = 0
while(count < 5):
print(“Hello”)
count= count + 1
i=100
while(i<=200):
print(i)
i+=40
n=30
i=5
s=0
while (i<n):
s+=i
i + = 5
print(“i=” , i)
print(“sum=”, s)

Example 19.
Calculation of factorial.

In figure 5.26, the while loop is used to calculate the factorial of a number in this program. the number is entered from the keyboard using the input function and is assigned to the variable ” number “.

# Calculation of factorial
factorial = 1
number = int(input(“Enter the number : “))
while(number > 1):
factorial = factorial * number
number = number -1
print (“The factorial is “, factorial)RUN
>>>
Enter the number: 5
The factorial is 120
>>>

Example 20.
Program to Print numbers 1 to 10 on different lines.

# Print numbers 1 to 10 using while loop
count = 0
while(count <=10):
print(count)
count= count + 1
print(“Done”)RUN
>>>
0
1
2
3
4
5
6
7
8
9
10
Done
>>>

The Python print( ) function by default ends with a new line. Python has a predefined format for using the print ( ) function; if you use print(a_variable) then it will go to the next line automatically. In Python 2, for printing code on the same line, a comma is used; but Python 3 provides one extra argument, i.e., end =” ” to print code on the same line.

Example 21.
Program to print numbers 1 to 10 on the same line.

# Print numbers 1 to 10 on the same line using while loop
count = 0
while(count < = 10) :
print(count, end =” ” )
count= count + 1
print(“\nDone”)RUN
>>>
0 1 2 3 4 5 6 7 8 9 10
Done
>>>

Example 22.
Program to print even numbers series.

# Print even numbers using while loop
count = 0
while(count <=20) :
print(count, end =” ” )
count= count + 2
print(“\nDone”)RUN
>>>
0 2 4 6 8 10 12 14 16 18 20
Done
>>>

Example 23.
Program to print odd numbers series.

# Print odd numbers using while loop
count = 1
while(count < 20):
print(count, end =” ” )
count= count + 2
print (“\nDone”)
RUN
>>>
1 3 5 7 9 11 13 15 17 19
Done
>>>

Example 24.
Program to print average of entered numbers.

# Program to print average of entered numbers
counter = 0
total = 0
number = 0
while number >= 0:
number = int(input(“Enter a positive number or a negative to exit: “))
total += number
counter += 1
avg = total / counter
print(“Average = : “,avg )RUN
>>>
Enter a positive number or a negative to exit: 4
Enter a positive number or a negative to exit: 2
Enter a positive number or a negative to exit: 4
Enter a positive number or a negative to exit: -4
Average = : 1.5
>>>

Example 25.
Program to find sum of all even and odd numbers up to specified number.

# Program to find sum of all even and odd numbers up to specified number
num = int(input(“Enter any number : “))
count= 1
sum_even= sum_odd= 0
while (count<=num):
if (count% 2) ==0:
sum_even += count
else:
sum_odd += count
count += 1
printC’Sum of all even numbers up to “,num ,” is “,sum_even)
print(“Sum of all odd numbers up to “,num ,” is “,sum_odd)RUN
>>>
Enter any number: 15
Sum of all even numbers up to 15 is 56
The Sum of all odd numbers up to 15 is 64
>>>

Let’s Try

What is printed by the following code fragments?

a = 0
while a > 100:
print(a)
a += 1
print ( )
i = 1
while True:
if i%2 == 0:
break
print(i)
i += 2

Let’s Try

What is the output of following code fragments?

result = 1
while result < 100:
result *= 2
print (result)
i = 1
while True:
if i%3 = = 0:
break
print(i)
i += 1

Recommended Reading On: Python Program to Enter Basic Salary and Calculate Gross Salary of an Employee

Leave a Reply

Your email address will not be published. Required fields are marked *