Python Working With While Loop

Python Working With While Loop

Let's start working with while loop in python. While loop is used to execute a block of code until certain condition is met. we can also terminate it before using the python keyword "break" If condition is not met then it will run for infinite number of times and we should avoid it. Unlike for loop it won't run for a fixed number of times.

Syntax of "while" loop in python:

while (condition):
    statement-1
    statement-2

Basic usage of "while" loop in python

  • Use Case: Print 15 table in python
number = 1
while (number <= 10):
    print("15 X ", number, "=", 15 * number)
    number = number + 1
# Output: 
# 15 X  1 = 15
# 15 X  2 = 30
# 15 X  3 = 45
# 15 X  4 = 60
# 15 X  5 = 75
# 15 X  6 = 90
# 15 X  7 = 105
# 15 X  8 = 120
# 15 X  9 = 135
# 15 X  10 = 150
  • When we run the above code it assigns the value 1 to the name "number". After, it starts the while loop execution. First it checks the condition "number <= 10" which is true(ie. 1 <= 10). So, it will executes the code inside the block of while loop. The first statement inside the while loop block is "print" so it executes and output will printed on the terminal/console("15 X 1 = 15"). We know a computer executes code line by line. So, It will execute the next statement"number = number + 1" . Now, number = 2. No other statements left inside the while loop block. So, again it goes to the while loop condition and repeats the same process until the condition (number <= 10 ) is false.

Practice "While" loop

  • Printing out a left-justified right triangle
*
**
***
****
*****
******
*******
********
*********

Solution:

start = 1
while(start < 10):
    print("*" * start)
    start = start + 1
  • Printing out a inverted left-justified right triangle
**********
*********
********
*******
******
*****
****
***
**
*

Solution:

start = 10
while(start > 0):
    print("*" * start)
    start = start - 1
  • Infinite While loop in python
while(True):
   print("Infinite Loop...")