Python while loop

  • while loop is used when we want to iterate execution of statements until a condition is met.
  • it's a indefinite loop

syntax of "while" loop

while <condition>:
    <statement-1>
    <statement-2>

square of numbers

write a program to print first five numbers

start = 1
while start < 5:
    print(start)
    start = start + 1
# output:
# 1
# 2
# 3
# 4
start = 1
while start < 5:
    print("*" * start)
    start = start + 1
# output:
# *
# **
# ***
# ****
start = 5
while start > 0:
    print("*" * start)
    start = start - 1
# output:
# *****
# ****
# ***
# **
# *

loop runs forever

while True:
   print("Infinite Loop...")

using "break" keyword

  • stop iteration of for loop when a condition is met

write a program if print given numbers i.e [1,2,3,4,5]. stop program if number equal to 3.

numbers = [1,2,3,4,5]
index = 0

while True:
    number = numbers[index]
    if number == 3:
        break
    print(number)
    index = index + 1
# output:
# 1
# 2

using "continue"

  • continue keyword used to skip the iteration.

write a program to print given numbers but skip iteration if number equal to 10

numbers = [1,2,3,10,4,5]
index = 0

while index < len(numbers):
    number = numbers[index]
    index = index + 1

    if number == 10:
        continue
    print(number)
# output:
# 1
# 2
# 3
# 4
# 5

References