While loop is used to execute statements until a condition is satisfied it. It performs iteration over the statements and it ends to iterate till the statement condition is fulfilled.
Following program inputs a integer number, for which if condition is satisfied for number being less than 8, it prints the number.
n = int(input("Enter value of a number n: "))
while n < 8:
print(n)
n = n + 1
Output :
Enter value of a number n: 4 4 5 6 7
While loop with else statement
Else statement is executed in the while loop if condition under the while loop becomes false. In the following program on entering a number 4, while loop is executed till number is less than 8, once after iteration the number is not less than 8, else statement is executed. On the second run, number entered is 9, since it does not fulfilled the while condition, it executed the else statement.
n = int(input("Enter value of a number n: "))
while n < 8:
print(n)
n = n + 1
else:
print("Number is greater than or equal to 8 ")
Output 1 :
Enter value of a number n: 4 4 5 6 7 Number is greater than or equal to 8
Output 2 :
Enter value of a number n: 9 Number is greater than or equal to 8
break and continue statement
Break statement is used to break the loop. Even if while condition is true break statement will break the loop. In the following program break statement is put for n = 4, so the loop will break at 4, and no further number will get printed.
n = int(input("Enter value of a number n: "))
while n < 8:
print(n)
if n == 4:
break
n = n + 1
Output :
Enter value of a number n: 1 1 2 3 4
Continue statement is used to break the loop at the continue position and then forward with the next one. In the following program iteration get stop at n = 4 and after that it get continued.