
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialAny computer program follows by default a sequential flow of execution of statements. Sometimes, the program flow may skip some statements as in the use of if – elif- else statements. If the program flow is directed towards any of earlier statements in the program, it constitutes a loop.

In above diagram, after execution of statement4, normally statement5 would have been executed. However, the control is directed to an earlier statement1. Hence, the section from statement1 to statement4 will be repeated and will keep repeating.
Sending the program control to earlier statement unconditionally causes infinite loop, which is not desired. Python uses while and for keywords to constitute conditional loop by which repeated execution of a block of statements is done until a Boolean expression is true.

In above diagram, if <expr> is true, the block (statement1, statement2, statement3) will be executed repeatedly as long as it is true. As soon as it doesn’t remain true, flow of the process comes out of loop and default path of program is undertaken.
while statement in python implements above algorithm.
General usage of while statement is as below:
while expr==True:
stmt1
stmt2
stmt3
stmt4
Here while statement is followed by a conditional expression and ends with : symbol which starts a block with increased indent. In this block statements to be executed repeatedly are entered. Such block is usually called body of loop. Repeated execution continues till the condition remains true. As and when it becomes false, repetition stops and subsequent statements at previous indent level will be executed.
Let us develop a Python program that successively takes number as input from user and calculates average of numbers as long as user enters any positive number. Here, the body of loop comprises input statement, statement to add input number and count number of input.
num=0
count=0
sum=0
while num>=0:
num=int(input("enter any number .. -1 to exit\n"))
if num>=0:
count=count+1 # this counts number of inputs
sum=sum+num # this adds input number cumulatively.
avg=sum/count
print ("numbers input:",count, "average:",avg)
As soon as a negative number is given, the loop terminates and displays average.
enter any number .. -1 to exit
10
enter any number .. -1 to exit
20
enter any number .. -1 to exit
30
enter any number .. -1 to exit
-1
numbers input: 3 average: 20.0
Python’s for keyword provides is mainly useful to iterate through items in sequence object. The body of the loop is executed for each member element in a sequence. No other Boolean expression is required to control the loop.
General usage of for statement in Python is as below:
for x in sequence:
stmt1
stmt2
stmt3
stmt4
The loop starts with variable x set to item at 0th index in the sequence. Statements with increased uniformly indented block after : symbol will be executed. Variable x now refers to each subsequent item and body of loop keeps on getting executed till the sequence is exhausted.
In Python, range object is an immutable sequence of numbers. It is useful in keeping count of repetition of a block in for loop. The range() function is used as follows:
range([start], stop, [step])
All three parameters have to be integer. Value of [start] parameter is 0 by default, unless given other integer. The only mandatory parameter for above function is stop. Last number in sequence is one less than stop parameter. Numbers in between are incremented with [step] value, which is 1 by default.
For example:
range(10) will generate 0,1,2,3,4,5,6,7,8,9
range(1,5) will generate 1,2,3,4
range(20,30,2) will generate 20,22,24,26,28
We can run for loop over a range. To print each number in given range
for num in range(1,11):
print (num)
print ("end of sequence")
Above code prints following output.
1
2
3
4
5
6
7
8
9
10
end of sequence
Following code calculates factorial value of a number taken as input.
Factorial of a certain number is product of all numbers between 1 and itself. We use range() function to obtain the sequence. Body of for loop performs cumulative multiplication of all numbers in the range.
num=int(input("enter a number"))
fact=1
for x in range(1,num+1):
fact=fact*x
print ("factorial of {} is {}".format(num,fact))
Sample run of above code shows factorial of 4
enter a number4
factorial of 4 is 24
As mentioned above, for loop iterates over elements in any sequence. We shall now learn to use for statement with sequence data types – string, list and tuple.
for char in " KnowledgeHut":
print (char)
Above example prints one character of given string at a time.
K
n
o
w
l
e
d
g
e
H
u
t
List and tuple object is also a sequence. If each item in list/tuple is to be processed, for statement is very much suitable. Following code computes average of all numbers in a list.
sum=0
numbers=[10,20,30,40]
for num in numbers:
sum=sum+num
avg=sum/len(numbers)
print ('average:', avg)
Output:
average: 25.0
Python’s dictionary is an unordered collection of Key-value pair items which do not have index. The for statement offers a convenient way to traverse a dictionary object. The items() method of dictionary object returns a list of tuples, each tuple having key and value corresponding to each item. We know that for loop can iterate through tuple. Following code uses for statement to print all key value pairs in
dict={1:100, 2:200, 3:300}
for pair in dict.items():
print (pair)
Following output will be displayed on Python console
(1, 100)
(2, 200)
(3, 300)
You can unpack each pair tuple to two variables in for statement to get key and value separately.
dict={1:100, 2:200, 3:300}
for k,v in dict.items():
print (k,v)
Output:
1 100
2 200
3 300
The keys() and values() methods of dictionary object also return list of keys and values from dictionary respectively. We can use them and iterate over each key/value using for loop.
dict={1:100, 2:200, 3:300}
for k in dict.keys():
print (k,dict.get(k))
Just as with if statement, Python allows else keyword to be used with for and while statements too. The else block appears after the body of the loop. The else block will be executed only after all iterations are completed. Program leaves the loop only after else block is executed.
for x in range(5):
print ("iteration no ", x+1)
else:
print ("in else block in loop")
print ("end of loop")
Output of above code confirms that else block in for loop will be executed when numbers in range are over.
iteration no 1
iteration no 2
iteration no 3
iteration no 4
iteration no 5
in else block in loop
end of loop
Use of else works well with while loop too.
x=0
while x<=5:
x=x+1
print ("iteration no ",(x+1)
else:
print ("This is last statement in loop")
print ("end of loop")
Normally, a loop (while or for) is employed for a certain number of repetitions of a block. The number of repetitions is decided by while condition. Length of sequence (string, list, tuple etc.) determines iterations of for loop. However, sometimes it is required that the loop be abandoned before completing stipulated number of iterations. You may also want next iteration to start before actually completing the current round of execution of body of the loop.
Python’s break and continue keywords for these purposes respectively. They act as loop control statements.
When this keyword is used in the middle of a loop, it abandons pending iterations of current loop and control of program jumps to the statement immediately after the body of the loop.
Typical use of break is found where you need to search for an object in a collection. You will have to execute comparison expression in a loop. However, if the required object is found, since there is no need to traverse remaining collection, remaining loop iterations are skipped using break statement.
Following diagram shows exact scenario.
In above diagram, looping block will be repeatedly executed till expression1 is true. However, inside the looping block, there is another expression2 which is verified for each iteration. As soon as it is found to be true, program control breaks out of the loop.
Python has break keyword to implement this functionality. General usage of break inside a while loop is as follows:
while expression1==True:
statement1
if expression2==True:
break
statement2
statement3
Usage of break within for loop is shown as below:
for x in sequence:
statement1
if expression==True:
break
statement2
statement3
Following program demonstrates use of break in a loop. It accepts a number as input and determines whether it is a prime number or not. By definition, n is prime if it is not divisible by any number between the range 2 to n-1.
The for loop reads one number from the range at a time as x and checks whether it divides n. If n%x returns 0, n is not prime and it is not necessary to check it for remaining numbers and loop needs to be terminated after displaying the message to that effect. It is done by break statement.
On the other hand if no number in the range is able to divide n, it is a prime number. Appropriate message is printed in else block.
num=int(input("enter a number"))
for x in range(2,num):
if num%x==0:
print ("{} is not prime".format(num))
break
else:
print ("{} is prime".format(num))
Output:
enter a number46
46 is not prime
enter a number12
12 is not prime
enter a number7
7 is prime
enter a number29
29 is prime
The continue statement works exactly opposite to that of break. Instead of leaving the loop, continue statement skips remaining statements in current loop and starts next iteration. Following diagram shows how continue works.
When expression in the loop (expression2) is true remaining statements in the current will be skipped and program control starts next round of iteration.
Usage of continue in Python is as below:
while expression1==True:
statement1
if expression2==True:
continue
statement2
statement3
Similarly, continue statement is used in for loop as below:
for x in sequence:
statement1
if expression==True:
continue
statement2
statement3
Following program uses continue keyword. User is asked to input a number till it is found to be even.
count=0
while True:
count=count+1
n=int(input("Enter a number"))
if n%2!=0:
continue
print ("Got an even number on attempt no. {}".format(count))
break
Output:
Enter a number1
Enter a number3
Enter a number2
Got an even number on attempt no. 3
pass keyword
The pass keyword is used as a nominal placeholder whenever a certain statement is required but it is not expected to do anything. Python interpreter treats it as a null statement. It is generally used as a dummy statement in a conditional code block.
if expression:
pass
The pass statement is generally used by programmers to design code framework. Initially the programmer will create no operation blocks using pass and eventually fill their functionality.
Nested Loops
If a loop (for loop or while loop) contains another loop in its body block, the two loops are nested. If outer loop is designed to perform x iterations and inner loop is designed to perform y repetitions, body block of inner loop will get executed x X y times.
for x in range(2):
for y in range(2):
print ("x={} y={}".format(x,y))
Here outer loop controlled by x will have two values (0,1) and y controlling inner loop also takes two values (0,1). Hence there will be four iterations of innermost statement.x=0 y=0
x=0 y=1
x=1 y=0
x=1 y=1
In this chapter, Python keywords related to looping mechanism have been described.