Python Essential Classroom Series – 13/Jul/2021

Looping

  • looping constructs allows us to execute one line or block repeatedly until some condition is met.
repeat below lines five times

until some value is something repeat the below lines
  • In python while will repeate the block until condition is true once the condition is false then the loop will be exited
index = 0
while index < 5:
    print("Hello World")
    index = index + 1
  • continue and break in loops:
    • While writing loops if we want to skip the current iteration then we use continue, if we want exit out of loop then we can use break
index = 0 
while index < 100:
    if index%2 == 0:
        index = index + 1
        continue
    print(index)
    index = index + 1
    if index == 10:
        break
print('Finished While loop')

  • Exercise: Write a while loop which will print all multiples of 3 between 10 and 100
index = 10
while index <= 100:
    if index%3 == 0:
        print(index)
    index = index + 1
print("End of the loop")
  • Exercise: Write a while loop which print all the multiples of 3 or 4 below 100
index = 1
while index <= 100:
    if index%3 == 0 or index % 4 == 0:
        print(index)
    index = index + 1
print("End of the loop")
  • Exercise: Write a while loop which will print all the multiples of 3 and 4
index = 1
while index <= 100:
    if index%3 == 0 and index % 4 == 0:
        print(index)
    index = index + 1
print("End of the loop")
index = 1
result = 0
while index < 1000:
    if index % 3 ==0 or index % 5 == 0:
        result = result + index
    index = index + 1
print(result)
  • Exercise: Write a program to calculate sum of squares on number below 10 Preview
result = 0
index = 1
while index < 10:
    result = result + (index ** 2)
    index = index + 1
print(result)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin