while loop in python

what is while loop

The while loop is used for executing a sequence of statement again and again on the basis of some test condition. If the test condition holds True, the body of the loop is executed, otherwise the control moves to the statement immediately following the while loop. Suppose, we wish to find the sum of all the numbers entered by a user until a null string (empty string: ' ') is entered as input. As we do not know in advance the count of numbers that the user will enter before entering a null string, we make use of a while loop in the script sumNumbers. Every time the user enters a string, its integer value is added to the old value of total (initialized to zero before the beginning of the loop). The process continues until the user enterd a null string as input. On encountering a null string, the test condition becomes False, the while loop terminates, and the control moves to , where we display the value of total.
total = 0
number = input('Enter a number: ')
while number != '':
total +=int(number)
number =input('Enter a number: ')
print('Sum of all input numbers is', total)

On executing the script sumNumber, Python prompts for numbers until the user enters null string as an input.
>>>
Enter a number: 2
Enter a number: 18
Enter a number: 15
Enter a number: 15
Sum of all input numbers is 50

infinite Loops

Sometimes we wand a while loop to continue indefinitely until an enabling event takes place, for example, the screen of a laptop may remain off until aley is pressed. For this purpose, we make use of a while loop based on a condition that always evaluates to True. Such a loop is known s an infinite loop, for example:
import time
while True:
try:
print('Loop processing....')
print('Use ctrl+c to break')
time.sleep(1)
except keyboardInterrupt:
print('User interrupted the loop... exiting...')
break

while Statement vs. for Statement

Having learned the use of while statement, let us use a while statement to rewrite the following piece of code:
for count in range(1, n + 1)
total +=count

The revised code is given below:
count = 1
while count < n+1:
total += count
count += 1

Note that for computing the sum of first few natural numbers, the use of for loop is more elegant and easy as compared to the while loop. Out of several control structures which may be used at a place, it is the discretion of the programmer to choose the simple and elegant one.

2 Responses to "while loop in python "

seo woker said...

This particular is usually apparently essential and moreover outstanding truth along with for sure fair-minded and moreover admittedly useful My business is looking to find in advance designed for this specific useful stuffs… python作业代写

GANGSTER said...

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. shipping containers brisbane

ads