Devops World
Published in

Devops World

While/For Loop Python

Check the updated DevOps Course.

Course Link:

YouTube link:

With while loop we can make block of code executed as long as while statement is True

test = 0
while ( test < 5):
print("hello")
test = test + 1
hello
hello
hello
hello
hello

Here as soon as the execution reaches the end of a while statement’s block, it jumps back to the start to re-check the condition. We are initializing test=0 and as long as the value of a test is less than 5, While checking the condition and prints the hello.

When execution runs through the loop we call it iteration we say this while loop iterates 5 times.

But let’s take a look at other two cases

  • If forget to initialize the value, I will receive an error
while n < 5:
print(n)
n = n+1

Output

Traceback (most recent call last):
File “/Users/plakhera/Documents/python_testing/test.py”, line 1, in <module>
while n < 5:
NameError: name ’n’ is not defined
Process finished with exit code 1
  • If I forget to increment the value, then it will become an infinite loop
n = 0
while n < 5:
print(
n)

Infinite Loop

>>> while True:… print(“hello”)hellohellohello

Since this condition is always True this will cause the loop to be executed forever. To come out of infinite loop use Ctrl+c

Break: Cause statement to jump out of loop, without re-checking the condition

test = 0
while (test < 10):
print(test)
test = test + 1
if test == 5:
break

Output

0
1
2
3
4

Continue

In the case of continue statement when the program execution reach the continue statement, program execution immediately jump back to the start off while loop and re-check the condition, and that is the reason test==5 never executed

test = 0
while (test < 6):
test = test + 1
if test == 5:
continue
print("Current Value of test: " + str(test))

Output

Current Value of test: 1
Current Value of test: 2
Current Value of test: 3
Current Value of test: 4
Current Value of test: 6

For Loop

For loop is used when we want to iterates a specific number of times.

for i in range(5):
print(i)

Output

0
1
2
3
4

Sum of first 100 number

total = 0
#Because it goes one less
for i in range(101):
total = total + i
print
(total)

Output

5050

OR one more favorite interview question, print all the even number between 0 to n number

for i in range(0,11,2):
print(
i)

Output

0
2
4
6
8
10

Let summarize

Let’s try to solve few more problem

In this problem we need to count number of vowels in a string

s = 'welcome to the world of python'
count = 0
for i in s:
if (
i == "a" or i == "e" or i == "i" or i == "o" or i == "u"):
count += 1

print(count)

Is there is any better way to write the same code?

s = 'welcome to the world of python'
count = 0
vowels
= ["a","e","i","o","u"]
for
i in s:
if
i in vowels:
count += 1

print(count)

But this code will fail if we have Vowels like AEIOU

s = 'welcOmE to the world of python'

It will return only 6 vowels

There are multiple ways to deal with this problem but the easiest way right now is the use of lower()

s = 'welcOmE to the world of python'
s = s.lower()
count = 0
vowels
= ["a","e","i","o","u"]
for
i in s:
if
i in vowels:
count += 1

print(count)

Later on when we jump to regular expression we will see we can solve the same problem using regular expression

>>> import re>>> s = ‘welcOmE to the world of python’>>> vowels = re.findall(‘[aeiou]’,s,re.IGNORECASE)>>> print(len(vowels))8

There might be a situation where we might need to know how many times the gives element is repeated in a string. There are number of ways to do that but the easiest way is to use collections module

>>> from collections import Counter>>> s‘welcOmE to the world of python’>>> a = Counter(s)>>> print(a)Counter({‘ ‘: 5, ‘o’: 4, ‘t’: 3, ‘w’: 2, ‘e’: 2, ‘l’: 2, ‘h’: 2, ‘c’: 1, ‘O’: 1, ‘m’: 1, ‘E’: 1, ‘r’: 1, ‘d’: 1, ‘f’: 1, ‘p’: 1, ‘y’: 1, ’n’: 1})

Let’s take one more case in which I need to find out how many times prash repeated in this string

s = 'hello my name is prash and the last name is prash too'
count = 0
for i in range(len(s)):
if
s[i:i+5] == "prash":
count += 1

print(count)
2

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prashant Lakhera

AWS Community Builder, Ex-Redhat, Author, Blogger, YouTuber, RHCA, RHCDS, RHCE, Docker Certified,4XAWS, CCNA, MCP, Certified Jenkins, Terraform Certified, 1XGCP