Table of Contents
Python loops are used to execute a block of code repeatedly. The Python while loop is a basic loop structure and the while loop runs until the condition is met and evaluated to True, and then execute the program block. The while loop is validated at the beginning of the while loop and when the expression evaluates to False.
Python while loop
As long as the condition is True, the while loop will execute the set of statements. For the below example, the loop will execute until variable b is no longer less than a by increasing variable b by 1 with each loop.
Input:
a = 25 b = 10 while b < a: print(f"Looping... {b} ") b += 1
Output:
Looping... 10 Looping... 11 Looping... 12 Looping... 13 Looping... 14 Looping... 15 Looping... 16 Looping... 17 Looping... 18 Looping... 19 Looping... 20 Looping... 21 Looping... 22 Looping... 23 Looping... 24
Python while…else Loop
The Python while loop will repeatedly test the conditions and, if it is True, the first block of program statements will be executed. By adding the else clause, when the condition is False, it will execute the first time it is tested. However, if the loops breaks or an exception is raised, it will terminate and the else clause will not be executed.
Input:
a = 0 b = 0 while (a < 20): b = b + a a = a + 1 else: print(f"The sum of the first 19 integers are {b} ")
Output:
Looping...: 10 Looping...: 11 Looping...: 12 Looping...: 13 Looping...: 14 Looping...: 15 Looping...: 16 Looping...: 17 Looping...: 18 Looping...: 19 Looping...: 20 Looping...: 21 Looping...: 22 Looping...: 23 Looping...: 24 The sum of the first 19 integers are 190
Python while…else Loop with if…else and break Statement
The break statement terminates the loop when a is the equ
Input:
a = 0 b = 0 while (a < 20): b = b + a a = a + 1 if (a == 15): break else : print(f"The sum of the first 19 integers are {b} ") print(f"The sum of {a} numbers is {b} ")
Output:
The sum of 15 numbers is 105