5TH Lecture
5TH Lecture
e
1) WHILE LOOP 2) FOR LOOP
g
Loops are used to repeat instructions.
olle
C
while Loops
pna
while condition :
A
#some work
THE VARIABLE USED IN THE LOOP IS CALLED THE ITERATOR
THE PROCESS OF CIRCLE IN THE LOOP OF PYTHON IS CALLED THE ITERATION
e
Print numbers from 1 to 100.
lleg
Co
Print numbers from 100 to 1.
pna
A
Print the multiplication table of a number n.
[1, 4, 9, 16, 25, 36, 49, 64, 81,100] THIS TYPE OF SEARCHING IS CALLED THE
LINEAR SEARCHING IN THE PYTHON
Break & Continue
e
Break : used to terminate the loop when encountered.
lleg
TERMINATE MEANS STOPPED WE ALSO USED THE BREAK KEYWORD TO PRINT ONLY FIRST
o
WHEN WE USED THE BREAK FUNCTION IN THE LOOP FINDING ELEMENT WHILE LOOP PRINT ALL FINDING ELEMENTS
OUR LOOP STOPPED THERE
C
Continue : terminates execution in the current iteration & continues execution of the loop
na
with the next iteration.
Loops in Python
ONE BY ONE
ge
Loops are used used for sequential traversal. For traversing list, string, tuples etc.
olle
C
for Loops
pna
WE USED THIS TYPE OF THE LOOP FOR THE DATA TYPE
for el in list:
A
ETC FOR LIST,STRING AND TUPLES
#some work
for el in list:
#some work
else:
else used as it doesn’t execute
#work when loop ends when break is used
Let‘s Practice
ge
using for
olle
Print the elements of the following list using a loop:
na C
[1, 4, 9, 16, 25, 36, 49, 64, 81,100]
Ap
Search for a number x in this tuple using loop:
range( )
NOT THE SEQUENCE OF THE DATA TYPE
ge
Range functions returns a sequence of numbers, starting from 0 by default, and increments by
lle
1 (by default), and stops before a specified number.
o
C
THERE ARE THREE MAIN POINTS FOR RANGE:
a
START==O AND ETC
STEP MEANS INCREASE == 1 AND ETC
range( start?, stop, step?)
n
STOP OR END == X
ge
using for & range( )
olle
Print numbers from 1 to 100.
na C
p
Print numbers from 100 to 1.
A
Print the multiplication table of a number n.
pass Statement PASS STATEMENT IS USED FOR SKIPPING BUT
NOT LIKE CONTINUE KEYWORD
ITS WORKS LIKE COMMENTS
ge
pass is a null statement that does nothing. It is used as a placeholder for future code.
olle
PASS STATEMENT IS USED IN THE LOOP
C
AND AS WELL AS IN CONDITIONAL STATEMENTS
na
for el in range(10):
Ap
pass
e
WAP to find the sum of first n numbers. (using while)
g
SOLVE THIS QUESTION WITH
e
THE FOR LOOP
Coll
pna
A
WAP to find the factorial of first n numbers. (using for) SOLVE THIS QUESTION WITH
THE WHILE LOOP