6_Loops
6_Loops
Learning objective
• Introduction to Loops
• Types of Loops
• For loop
• While loop
• Nested loop
• Loop control statements
• Break, continue and pass statement
• Difference between pass statement and comments
Introduction to Loops
• There could be a situation where you have to execute a block of
code several numbers of times.
uniqueDigit = set(num)
#print(uniqueDigit)
• Once the condition is false, the control will come out of the loop.
While loop syntax
while expression:
statement(s)
• Once you “nest” two loops, the outer loop takes control of the
amount of complete repetitions of the inner loop.
•
• Thus inner loop is executed N- times for each execution of outer
loop.
for x in range(1,6):
for y in range (1, x+1):
print(x, end=" ")
end parameter specifies what should be printed at the end of the output, instead of the default newline (\n)
Write a program to display the following
output
1
22
333
4444
55555
Infinite loop
• A loop becomes infinite loop if a condition never becomes FALSE.
• You must use caution when using while loops because of the
possibility that this condition never resolves to a FALSE value.
• The most common use for break is when some external condition
is triggered requiring a hasty exit from a loop.
• The break statement can be used in both while and for loops.
Break statement example
for x in range(11,21):
if(x==17):
break
print(x, end=" ")
Continue statement
• Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
• The continue statement can be used in both while and for loops.
Continue statement example
for x in range(11,21):
if(x==17):
continue
print(x, end=" ")
Pass statement
• The pass statement in Python is used when a statement is
required syntactically but you do not want any code to execute.
age = 10
if age > 10:
pass
else:
print(“if with placeholder for future condition")
Pass vs Comment
Pass vs Comment