Python while Loop


  • The while statement allows us to repeatedly execute a block of statements as long as a condition is true

  • Indentation and Colon should be respected.

Syntax :

                    
while test_expression:
    statement(s)  must be indented
                

In while loop, test expression is checked first. If test_expression is evaluates True, then the statements within the body of loop executes.After one iteration, the test expression is checked again. This process will continues until the test_expression evaluates to False


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

Flow chart of while loop

prowessapps.in

Example :

count = 0
while (count < 9):
   print("The count is:", count)
   count = count + 1

print("Good bye!")
OUTPUT
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.


Example :

Program to add natural numbers upto n
# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)
OUTPUT
Enter n: 10
The sum is 55

while loop with else :

Python supports to have an else statement associated with a loop statement.

  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

  • The while loop can be terminated with a break statement. In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Example

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")
OUTPUT
Inside loop
Inside loop
Inside loop
Inside else

Next topic is for Loop




 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved