WHAT ARE LOOPS?
print(“Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
print("Mathew")
3
Consider I want to print my name 10 times.
print(“Mathew"
)
OR
4.
A loop isused to repeat an instruction multiple times until a condition goes wrong.
4
“
5.
There are twoprimitive loop types in Python –
5
Types of Loops in Python
For in
loop
While
loop
6.
A for inloop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string)
6
For in Loops
Syntax –
for counter in sequence :
statement(s)
7.
A while loopis used to execute a set of statements as long as a condition is true.
7
While Loops
Syntax –
while condition :
statement(s)
8.
# for inloop
iterable_objs = range(6)
for iterator in iterable_objs:
print(iterator)
8
# while loop
i = 42
while not(i<=10):
print(i)
i -= 7
9.
# for inloop
numbers = [0,1,2,3,4,5]
for num in numbers:
print(num)
9
# for in loop
for x in range(6):
print(x)
10.
# for inloop
for x in range(3,6):
print(x)
10
# for in loop
for x in range(6,3,-1):
print(x)
# for in loop
for x in range(3,8,2):
print(x)
3
4
5
3
5
7
6
5
4
11.
With the elsestatement, we can run a block of code once a condition is no longer true.
11
The else Statement
Syntax –
while condition :
statement(s)
else :
statement(s)
12.
Loop control statementschange execution from its normal sequence. There are 3 types –
12
Loop Control Statements
break
statement
continue
statement
pass
statement
13.
# Break
for xin range(6):
if x==4:
break
print(x)
# Continue
for y in “Mathew":
if y=='h':
continue
print(y)
# Pass
mylist = [1,2,5,8,6,3]
for c in mylist:
pass
13
14.
For in loopdefault increments by 1.
Else statement in loop won’t work if the loop is terminated by
break statement.
Nested loop is a type of non primitive loops in python.
In this, we can use multiple for or while loops inside a for or while
loop.
Points to be noted
15.
LET’S REVIEW TODAY’SLEARNING
What is Loops in Python?
In this, we have understood the basic
meaning of loop and have gone
through definition of loops.
Else statement in Loop
Here we have learned about the else
statement. It’s implementation and
where it works.
Benefits of using Loop
Here we have gone through some
examples which cleared why loops are
efficient and less time consuming.
Types of Loop in Python
We have learned the two primitive
types of loops in Python and their
implementation.
Loop Control Statements
Here, we have gone through the three
different loop statements in Python.
How and where they are used.
Points to be noted
Here we have covered some extra
points related to our topics.