Day 10: Loops in Python

Just like javascript or any other programming languages, python offers ways to run repetitive code using while or for loops.

While loop

number = 10

while number > 0:
   print(number)
   number -= 1
# 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

The while expression runs as long as the expression remains true.

For loop

for i in "soumil": #String are iterable
   print (i)

's'
'o'
'u'
'm'
'i'
'l'

total = 0
for ltr in "euphoria":
  if ltr in "aeiou":
     total += 1

print (total)  # 5

Break & Continue keywords

Python has break & continue keywords that affect loops.

The break is used for exiting a loop. Its often used within a conditional block, meanwhile the continue skips current iteration and goes to the next.

name = "Soumil Roy"
total_vowels = 0

for char in name:
   if (char in "R"):
      break;
   print (char)	
# S, o, u, m, i, l 
# Breaks loop from R onwards
for char in "SOUMIL":
  if char in "AEIOU":
     continue
  print (char) # Skip all vowels S,M,L

What’s your Reaction?
+1
0
+1
0
+1
0

Published by Soumil Roy

I'm a Full-Stack Developer with 7+ years of experience in Web design & development .Currently building expertise in React, TypeScript & GraphQL

Leave a comment

Your email address will not be published.

Open WhatApp
Hello 👋 Click the button below connect with me.