Translated Presentation
Translated Presentation
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
In Python programm i ng, fl ow c ontrol i s the order i n whi c h s tateme nts or bl oc k s of c od
bas ed on a c ondi ti on.
Cont rol Flow Statements
T heflow control statements are divided into
three categories
1.
Conditional statements
2.
It erative statements.
3.
Transferstatements
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
In Python programm i ng, fl ow c ontrol i s the order i n whi c h s tateme nts or bl oc k s of c od
bas ed on a c ondi ti on.
Cont rol Flow Statements
T heflow control statements are divided into
three categories
1.
Conditional statements
2.
It erative statements.
3.
Transferstatements
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
It erative statements.
Wh atis fo r lo op in
Pytho n
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
It erative statements.
Wh atis fo r lo op in
Pytho n
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Syntax of
for
loop
for
i
in
ran ge
/
se que ncee
:
s tat emen t
1
s tat emen t
2
statementn
i
i s the i terating v ariabl e
,
range
s pec i fi es how many ti mes the l oop s houl drun.
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Syntax of
for
loop
for
i
in
ran ge
/
se que ncee
:
s tat emen t
1
s tat emen t
2
statementn
i
i s the i terating v ariabl e
,
range
s pec i fi es how many ti mes the l oop s houl drun.
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
for
forl oop with range
()
The range() function returns a
sequence of numbers starting
from
0
(bydefault)if the
initial limitis not specified
and it increments by
1
(by
default) until a final limit is
reached
sum =
0
for
i
in
range(
2
,
22
,
2
):
sum
= sum +
i
print(sum
)
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
P yt hon for
loop
for loop with
Tup le
A tuple is simila r to a lis t but is immutable . You ca n loop through it in the sa me w ay as a
m y _ tuple
=(
10
,
20
,
30
,
40
,
50
)
; f or
i t emi n
m y _ t uple
: ; print(item
)
for loop with
Diction ary
d ic tio nar ysto re skey
-
value p airs. You can loopthrou ghkeys, valu e s, orb oth .
my_dict
=
{
'a'
:
1
,
'b'
:
2
,
'c'
:
3
}
# Looping through keys
for
key
in
my_dict
:
print
(key)
#
Looping through values
for
value
in
my_dict.values
():
print
(value)
#
Looping through keys and values
for
key, value
in
my_dict.items
():
print
(key, value)
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
P yt hon for
loop
for loop with
Tup le
A tuple is simila r to a lis t but is immutable . You ca n loop through it in the sa me w ay as a
m y _ tuple
=(
10
,
20
,
30
,
40
,
50
)
; f or
i t emi n
m y _ t uple
: ; print(item
)
for loop with
Diction ary
d ic tio nar ysto re skey
-
value p airs. You can loopthrou ghkeys, valu e s, orb oth .
my_dict
=
{
'a'
:
1
,
'b'
:
2
,
'c'
:
3
}
# Looping through keys
for
key
in
my_dict
:
print
(key)
#
Looping through values
for
value
in
my_dict.values
():
print
(value)
#
Looping through keys and values
for
key, value
in
my_dict.items
():
print
(key, value)
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
P yt hon for
loop
for loop with
Set
A set is a n uno rdered col le c tio no f unique items . Yo u can lo o p thro ugh a set just likea
my_set
={
100
,
200
,
300
,
400
,
500
}
;for
itemin
my_set
:
;pri nt (item
)
for loop with
String
A str ing is a s equenc e of cha r ac ter s.You ca n loop through the cha r ac ter s of a str ing us
for
lo o p.
my_string
= "hell o " fo r c har in
my_string
: print(c har)
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
P yt hon for
loop
for loop with
Set
A set is a n uno rdered col le c tio no f unique items . Yo u can lo o p thro ugh a set just likea
my_set
={
100
,
200
,
300
,
400
,
500
}
;for
itemin
my_set
:
;pri nt (item
)
for loop with
String
A str ing is a s equenc e of cha r ac ter s.You ca n loop through the cha r ac ter s of a str ing us
for
lo o p.
my_string
= "hell o " fo r c har in
my_string
: print(c har)
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Exampl e :
Calculate
the sq uare of ea ch nu mbe r of list
numbers = [
1
,
2
,
3
,
4
,
5
]
#iterate over each element
in list
num
for
i
in
numbers:
# ** exponent operator
square
=
i
**
2
print
(
"Squareof:"
,
i
,
"is:"
, square)
Note
:
The l oopruns ti l l i t reach es the l as t el ement i n the
s equenc e. If
it reac hes the last element in the
sequence,
i t exits the l oop. otherwi s e, i t k eeps on
exec uti ng the s tateme nts presen t under the l oop
s
body
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Exampl e :
Calculate
the sq uare of ea ch nu mbe r of list
numbers = [
1
,
2
,
3
,
4
,
5
]
#iterate over each element
in list
num
for
i
in
numbers:
# ** exponent operator
square
=
i
**
2
print
(
"Squareof:"
,
i
,
"is:"
, square)
Note
:
The l oopruns ti l l i t reach es the l as t el ement i n the
s equenc e. If
it reac hes the last element in the
sequence,
i t exits the l oop. otherwi s e, i t k eeps on
exec uti ng the s tateme nts presen t under the l oop
s
body
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Wh y u se
for
loop
?
Definite Iteration
: W hen we k now how many ti mes we wanted to run a l oop, then we us e
c ount
-
c ontroll ed
l oops
s uc h as for l oops . It i s al s o k nown as defi ni tei teration . For exampl e, Cal c ul ateth
50
s tudents . here we k now we need to i terate a l oop
50
ti mes (
1
i teration for eac h s tudent).
s complexity
: Loop repeats a s pec i fi c bl oc k of c ode a fi xed numbe r of ti mes . It reduce s
the repetiti on of l i nes of c ode, thus reduci ng the c ompl exi ty of the c ode. Us i ng
for
l oops and
while
l oops
we c an autom ate and repeat tas k s i n an effi c i ent ma nner.
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Wh y u se
for
loop
?
Definite Iteration
: W hen we k now how many ti mes we wanted to run a l oop, then we us e
c ount
-
c ontroll ed
l oops
s uc h as for l oops . It i s al s o k nown as defi ni tei teration . For exampl e, Cal c ul ateth
50
s tudents . here we k now we need to i terate a l oop
50
ti mes (
1
i teration for eac h s tudent).
s complexity
: Loop repeats a s pec i fi c bl oc k of c ode a fi xed numbe r of ti mes . It reduce s
the repetiti on of l i nes of c ode, thus reduci ng the c ompl exi ty of the c ode. Us i ng
for
l oops and
while
l oops
we c an autom ate and repeat tas k s i n an effi c i ent ma nner.
If
-
else is used when conditional iteration is needed. For example, print
student nameswho got more than
80
percent.
The if
-
else statementchecks the condition and iftheconditionis Trueit
executes the block of code present insidethe if block and if the
condition is False, it willexecute the block of code present inside the
else block.
for
i
in
ran ge(
1
,
11
):
if
i
%
2
==
0
:
print
(
'Ev enNu mbe r:'
,
i
)
else
:
print
(
'Od dNum ber :'
,
i
)
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
If
-
elsein
for
loop
If
-
else is used when conditional iteration is needed. For example, print
student nameswho got more than
80
percent.
The if
-
else statementchecks the condition and iftheconditionis Trueit
executes the block of code present insidethe if block and if the
condition is False, it willexecute the block of code present inside the
else block.
for
i
in
ran ge(
1
,
11
):
if
i
%
2
==
0
:
print
(
'Ev enNu mbe r:'
,
i
)
else
:
print
(
'Od dNum ber :'
,
i
)
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Lo opCo ntrolStatem ents in for
loo p
Loop control statements change the normalflow of execution. It is used when you
want to exit a loop or skipa part of theloop based onthe given condition. It
also knows astransfer statements
Break for
loop
The break statement is usedto
terminate the loop.
Youcan use the break
statement whenever you wantto
stop the loop
. Just you need to type the break
inside the loop after the statement, after which you want to break the loop.
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Lo opCo ntrolStatem ents in for
loo p
Loop control statements change the normalflow of execution. It is used when you
want to exit a loop or skipa part of theloop based onthe given condition. It
also knows astransfer statements
Break for
loop
The break statement is usedto
terminate the loop.
Youcan use the break
statement whenever you wantto
stop the loop
. Just you need to type the break
inside the loop after the statement, after which you want to break the loop.
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Loop ControlStatementsinfor
loop
Break for
loop
Example: break the loop if number a number is greater than
15
numb ers
=
[
1
,
4
,
7
,
8
,
15
,
20
,
35
,
45
,
55
]
for
i
in
num ber s
:
if
i
>
15
:
# br eak the lo op
b re a k
els e
:
p rin t
(
i
)
Note:
If the break statement is used
inside a nested loop (loop inside
another loop), it will terminate the
innermost loop.
# Ne ste d lo o p w ith a b reak sta teme nt
fo r
i
in
ra n ge
(
1
,
4
):
# O u te r l oo p
for
j
in
r a nge
(
1
,
4
):
# I nner lo op
p rin t
(
f
"i
=
{
i
}
, j=
{
j
}
"
)
if
j
==
2
:
bre ak
# B reak s th e in ner loo p on ly w hen j i s
2
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Loop ControlStatementsinfor
loop
Break for
loop
Example: break the loop if number a number is greater than
15
numb ers
=
[
1
,
4
,
7
,
8
,
15
,
20
,
35
,
45
,
55
]
for
i
in
num ber s
:
if
i
>
15
:
# br eak the lo op
b re a k
els e
:
p rin t
(
i
)
Note:
If the break statement is used
inside a nested loop (loop inside
another loop), it will terminate the
innermost loop.
# Ne ste d lo o p w ith a b reak sta teme nt
fo r
i
in
ra n ge
(
1
,
4
):
# O u te r l oo p
for
j
in
r a nge
(
1
,
4
):
# I nner lo op
p rin t
(
f
"i
=
{
i
}
, j=
{
j
}
"
)
if
j
==
2
:
bre ak
# B reak s th e in ner loo p on ly w hen j i s
2
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Loop ControlStatementsinfor
loop
ContinueStatementinfor
loop
i n a giv en string.
name
=
"
m ari ya
menn en
"
coun t
=
0
for
cha r
in
nam e
:
if
char
!=
'm'
:
c on t in u e
els e
:
c oun t
=
c ount
+
1
prin t
(
' Tota l nu mber of m i s :'
,
c ount
)
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Loop ControlStatementsinfor
loop
ContinueStatementinfor
loop
i n a giv en string.
name
=
"
m ari ya
menn en
"
coun t
=
0
for
cha r
in
nam e
:
if
char
!=
'm'
:
c on t in u e
els e
:
c oun t
=
c ount
+
1
prin t
(
' Tota l nu mber of m i s :'
,
c ount
)
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Lo opControlStatem ents in for loop
Pass Statementinfor loop
The pass statement is a null statement, i.e., nothing
happens when the statement is executed.
num
=
[
1
,
4
,
5
,
3
,
7
,
8
]
for
i
in
num
:
# calculate multiplication in future if required
pass
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Lo opControlStatem ents in for loop
Pass Statementinfor loop
The pass statement is a null statement, i.e., nothing
happens when the statement is executed.
num
=
[
1
,
4
,
5
,
3
,
7
,
8
]
for
i
in
num
:
# calculate multiplication in future if required
pass
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Else b lo ckin
for
loop
In Python, for
-
loop can have the else block, which
will be
executedwhen theloopterminatesnormally.
Defining the else part withfor loop is optional.
Else
block will be skipped when
1.
for
loop terminate abruptly
2.
the break statement is usedto break the loop
Ex am pl e
:
E l se bl oc k i n fo r l o op
In t his exa m ple , we ar e pr i nti ng t he firs t
5
numb ers , an d
afte r s ucce s sfu l ex ecu tion of a lo op, the int erpr ete r wi l l
exec ute the els e bl ock .
for
i
in
range
(
1
,
6
):
print
(
i
)
else
:
print
(
"Done"
)
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Else b lo ckin
for
loop
In Python, for
-
loop can have the else block, which
will be
executedwhen theloopterminatesnormally.
Defining the else part withfor loop is optional.
Else
block will be skipped when
1.
for
loop terminate abruptly
2.
the break statement is usedto break the loop
Ex am pl e
:
E l se bl oc k i n fo r l o op
In t his exa m ple , we ar e pr i nti ng t he firs t
5
numb ers , an d
afte r s ucce s sfu l ex ecu tion of a lo op, the int erpr ete r wi l l
exec ute the els e bl ock .
for
i
in
range
(
1
,
6
):
print
(
i
)
else
:
print
(
"Done"
)
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Reversefor
loop
There are three w ays to iterating the
for
loop backw ard
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Reversefor
loop
There are three w ays to iterating the
for
loop backw ard
In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop
Synta xo fne sted for loo ps
:
# outer for loop
for
element
in
sequence
# inner for loop
for
element
in
sequence:
body of inner
for
loop
body of outer
for
loop
other statements
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Nes ted f o r l oop s
In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop
Synta xo fne sted for loo ps
:
# outer for loop
for
element
in
sequence
# inner for loop
for
element
in
sequence:
body of inner
for
loop
body of outer
for
loop
other statements
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Nes ted f o r l oop s
Example
: Nested for l oop to pri nt the foll owi ng pattern
*
**
***
****
*****
rows
=
6
# outer loop
for
i
in
range
(
0
,
rows
):
# inner loop
for
j
in
range
(
1
,
i
+
1
):
print
(
"*"
,
end
=
""
)
print
(
''
)
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Nes ted f o r l oop s
Example
: Nested for l oop to pri nt the foll owi ng pattern
*
**
***
****
*****
rows
=
6
# outer loop
for
i
in
range
(
0
,
rows
):
# inner loop
for
j
in
range
(
1
,
i
+
1
):
print
(
"*"
,
end
=
""
)
print
(
''
)
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
While loop inside for
loop
The wh ileloo p isan e ntr y
-
controlled loo p ,and a for lo op isa cou nt
-
controlledloo p .
# outer loop
for
i
in
range
(
1
,
6
):
print
(
'Multiplicationtable of:'
,
i
)
count
=
1
# inner loop to print multiplication table of current number
while
count
<
11
:
print
(
i
*
count
,
end
=
''
)
count
=
count
+
1
print
(
'
\
n
'
)
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
While loop inside for
loop
The wh ileloo p isan e ntr y
-
controlled loo p ,and a for lo op isa cou nt
-
controlledloo p .
# outer loop
for
i
in
range
(
1
,
6
):
print
(
'Multiplicationtable of:'
,
i
)
count
=
1
# inner loop to print multiplication table of current number
while
count
<
11
:
print
(
i
*
count
,
end
=
''
)
count
=
count
+
1
print
(
'
\
n
'
)
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
forloopin one
line
Example
: Print the even numbers by adding
1
to the odd numbers
in
the
list
odd
=
[
1
,
5
,
7
,
9
]
even
=
[
i
+
1
for
i
in
odd
if
i
%
2
==
1
]
print
(
even
)
formulate thefor loop statement in one line to reduce the number of lines of code.
P yt hon for
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
forloopin one
line
Example
: Print the even numbers by adding
1
to the odd numbers
in
the
list
odd
=
[
1
,
5
,
7
,
9
]
even
=
[
i
+
1
for
i
in
odd
if
i
%
2
==
1
]
print
(
even
)
formulate thefor loop statement in one line to reduce the number of lines of code.
P yt hon for
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Accessing the
index
in
for
loop
P yt hon for
loop
he
enumerate()
function is useful w henw ew antedto access both value and its index number
or any sequence such as list or string.
The enumerate() adds a counter to iteration and returnsit in the form of an enumerable
object.
numbers = [
4
,
2
,
5
,
7
,
8
]
for
i
, v in enumerate(numbers):
print(
i,v
)
dialo gue =
" Remem ber ,Re d,ho pe isa good
thing ,m aybe the bes tof thin gs, and nog ood
thing ev erd ies"
#s plit onw hit espa ce
fo r
w ord
in
dialo gue.split
(): pri nt(wo rd)
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterat ivest at ements.
Accessing the
index
in
for
loop
P yt hon for
loop
he
enumerate()
function is useful w henw ew antedto access both value and its index number
or any sequence such as list or string.
The enumerate() adds a counter to iteration and returnsit in the form of an enumerable
object.
numbers = [
4
,
2
,
5
,
7
,
8
]
for
i
, v in enumerate(numbers):
print(
i,v
)
dialo gue =
" Remem ber ,Re d,ho pe isa good
thing ,m aybe the bes tof thin gs, and nog ood
thing ev erd ies"
#s plit onw hit espa ce
fo r
w ord
in
dialo gue.split
(): pri nt(wo rd)
Python
Intr oduction
P ython Input: Take Input from
User
In
P ython, Us ing the
input()
function, w etake input from a user, and using the
print()
function,
w edisplay output on the screen. Using the
input()
function, user s can give any information to
the application in the strings or numbers format.
■■■■■: Python
Intr oduction
P ython Input: Take Input from
User
In
P ython, Us ing the
input()
function, w etake input from a user, and using the
print()
function,
w edisplay output on the screen. Using the
input()
function, user s can give any information to
the application in the strings or numbers format.
The
prompt
argument i s opti onal .The
prompt
argument i s us ed to di s pl ay a mes s age to the us er.
For example, the prompt i s ,
W hen the
input()
func ti on executes , the program wai ts unti l a us er enters s ome v al ue.
Final l y,The
input()
func ti on reads a v al uefrom the s c reen, c onv erts i t i nto a s tring, and returns i t
to the c all i ngprogram.
Note
: I f you ent eranint egerorf loat number, s t ill, it will c onvert it int oas t ring.
■■■■■: Python
Intr oduction
P ython Input: Take Input from
User
How
input()
Fu nctio n
Works
syntax
input
([p romp t])
The
prompt
argument i s opti onal .The
prompt
argument i s us ed to di s pl ay a mes s age to the us er.
For example, the prompt i s ,
W hen the
input()
func ti on executes , the program wai ts unti l a us er enters s ome v al ue.
Final l y,The
input()
func ti on reads a v al uefrom the s c reen, c onv erts i t i nto a s tring, and returns i t
to the c all i ngprogram.
Note
: I f you ent eranint egerorf loat number, s t ill, it will c onvert it int oas t ring.
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
The whil e lo o p statementrepeatedly exec utes aco de blo c k whil ea partic ula r co nditi o n is
count =
1
# co nditi o n: Run lo o p till co unt is l essthan
3
whil eco unt <
3
:
print(co unt)
co unt = co unt +
1
We us e a whi l el oop when the numbe r of i teration i s not k nown beforehand. For exampl e, i f
a us er to gues s your l uc k numbe r between
1
and
10
, we don
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
The whil e lo o p statementrepeatedly exec utes aco de blo c k whil ea partic ula r co nditi o n is
count =
1
# co nditi o n: Run lo o p till co unt is l essthan
3
whil eco unt <
3
:
print(co unt)
co unt = co unt +
1
We us e a whi l el oop when the numbe r of i teration i s not k nown beforehand. For exampl e, i f
a us er to gues s your l uc k numbe r between
1
and
10
, we don
t k no w ho w m an y atte m pts the us er m ay ne ed
to gues s the c orrec t numbe r. In s uc h c as es , us e a whi l e l oop.
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Synta xf orw hile
loo p
while
co ndit ion:
# Bloc kof sta teme nt(s)
The whil e stateme ntc hec ks the co nditi o n. The conditio n must return a
bo o lea n
val ue. EitherTrue o r Fal se.
N ext, If the co nditio n eval uates to true, the whilestatementexec utes the statements prese nt i
The whil e stateme ntcontinues c hec ki ng the conditio n in ea c h iteratio n and kee ps exec utin
conditio n becom es fa ls e.
count =
1
# run l oop ti l l count is l ess tha n
5
whi l e count <
5
:
print(cou nt )
cou nt = cou nt +
1
Note
:The lo opwi th continuing foreverif youforgotto increment counter inthe aboveexample
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Synta xf orw hile
loo p
while
co ndit ion:
# Bloc kof sta teme nt(s)
The whil e stateme ntc hec ks the co nditi o n. The conditio n must return a
bo o lea n
val ue. EitherTrue o r Fal se.
N ext, If the co nditio n eval uates to true, the whilestatementexec utes the statements prese nt i
The whil e stateme ntcontinues c hec ki ng the conditio n in ea c h iteratio n and kee ps exec utin
conditio n becom es fa ls e.
count =
1
# run l oop ti l l count is l ess tha n
5
whi l e count <
5
:
print(cou nt )
cou nt = cou nt +
1
Note
:The lo opwi th continuing foreverif youforgotto increment counter inthe aboveexample
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Synta xf orw hile
loo p
while
co ndit ion:
# Bloc kof sta teme nt(s)
The whil e stateme ntc hec ks the co nditi o n. The conditio n must return a
bo o lea n
val ue. EitherTrue o r Fal se.
N ext, If the co nditio n eval uates to true, the whilestatementexec utes the statements prese nt i
The whil e stateme ntcontinues c hec ki ng the conditio n in ea c h iteratio n and kee ps exec utin
conditio n becom es fa ls e.
count =
1
# run l oop ti l l count is l ess tha n
5
whi l e count <
5
:
print(cou nt )
cou nt = cou nt +
1
Note
:The lo opwi th continuing foreverif youforgotto increment counter inthe aboveexample
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Synta xf orw hile
loo p
while
co ndit ion:
# Bloc kof sta teme nt(s)
The whil e stateme ntc hec ks the co nditi o n. The conditio n must return a
bo o lea n
val ue. EitherTrue o r Fal se.
N ext, If the co nditio n eval uates to true, the whilestatementexec utes the statements prese nt i
The whil e stateme ntcontinues c hec ki ng the conditio n in ea c h iteratio n and kee ps exec utin
conditio n becom es fa ls e.
count =
1
# run l oop ti l l count is l ess tha n
5
whi l e count <
5
:
print(cou nt )
cou nt = cou nt +
1
Note
:The lo opwi th continuing foreverif youforgotto increment counter inthe aboveexample
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Examp le:
count
=
0
number
=
180
while
number
>
10
:
# divide number by
3
number
=
number
/
3
# increase count
count
=
count
+
1
print
(
'Total iteration required'
,
count
)
Fl ow chartof w hile
loop
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Examp le:
count
=
0
number
=
180
while
number
>
10
:
# divide number by
3
number
=
number
/
3
# increase count
count
=
count
+
1
print
(
'Total iteration required'
,
count
)
Fl ow chartof w hile
loop
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Why and Wh e n toUse wh ile Loo p in
P y tho n
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Why and Wh e n toUse wh ile Loo p in
P y tho n
Indefinite Iteration
: The whi l el oop wi l l run as often as nec es s ary to c ompl ete a partic ul ar task .
W hen the us er does n
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Why and Wh e n toUse wh ile Loo p in
P y tho n
Indefinite Iteration
: The whi l el oop wi l l run as often as nec es s ary to c ompl ete a partic ul ar task .
W hen the us er does n
Reduce complexit y
: whi l el oop i s eas y to write. us i ngthe l oop, we don
Infinite loop
: If the c ode i ns i dethe whi l e l oopdoes n
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Why and Wh e n toUse wh ile Loo p in
P y tho n
Reduce complexit y
: whi l el oop i s eas y to write. us i ngthe l oop, we don
Infinite loop
: If the c ode i ns i dethe whi l e l oopdoes n
Break Statement
Cont in ueStatement
Pass Statement
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Transfe rstate me ntsin wh ile
loo p
It i s us ed when you want to exi t a l oop or s k i pa
part of the l oopbas ed on the gi v en c ondi ti on.It
al s ok nows as transfe r s tateme nts .
Break Statement
Cont in ueStatement
Pass Statement
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Nested
while
loops
whi le loop ins ide awhi le loop
while
ex pres sion:
while
ex pres sion:
statemen
(s
)of innerloop
s tat emen
(s
)o fo uter loop
for l oo pin sidea w hil elo op
We can also use
for loop
inside a w hileloop as a nested loop.
i
=
1
# outer whileloop
while
i
<
5
:
# nested for loop
for
j
in
range
(
1
,
i
+
1
):
print
(
"*"
,
end
=
""
)
print
(
''
)
i
=
i
+
1
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Nested
while
loops
whi le loop ins ide awhi le loop
while
ex pres sion:
while
ex pres sion:
statemen
(s
)of innerloop
s tat emen
(s
)o fo uter loop
for l oo pin sidea w hil elo op
We can also use
for loop
inside a w hileloop as a nested loop.
i
=
1
# outer whileloop
while
i
<
5
:
# nested for loop
for
j
in
range
(
1
,
i
+
1
):
print
(
"*"
,
end
=
""
)
print
(
''
)
i
=
i
+
1
Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Else statement in
w hil e
loop
The
else block w illnot execute in the follow ing conditions:
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Else statement in
w hil e
loop
The
else block w illnot execute in the follow ing conditions:
Reverse a string or li st
# reverse while loop
i
=
10
while
i
>=
0
:
print(
i
, en d= ' ')
i
=
i
-
1
name = "Jess a"
i
=
0
res =
len
(name)
-
1
while
i
<= res :
print(nam e[
i
])
i
=
i
+
1
■■■■■: Python
Intr oduction
Py thon Co ntrolFlow Statem ents and Lo ops
2.
Iterativestat ements.
P yt hon while
loop
Reverse w hi lelo op
A reverse lo o p mea ns a n iterating lo o p in the bac kwa rd direc tio n. A sim ple exa mple i
Reverse a string or li st
# reverse while loop
i
=
10
while
i
>=
0
:
print(
i
, en d= ' ')
i
=
i
-
1
name = "Jess a"
i
=
0
res =
len
(name)
-
1
while
i
<= res :
print(nam e[
i
])
i
=
i
+
1
Python
Intr oduction
P yt hon
Functions
The
fun ction isa blo ckof cod edefine d witha
name .
We
use
f u nc tio n s
whe never
we
need
to
per fo rm
t he
sa me
task
multi p le
times
without
writing
t he
same
co de
agai n
.
It
can
take
arguments
and
returns
the
val ue
.
Python has a DRYprinciple like
other programming languages. DRY
stands for Don
t RepeatYourself.
Function improves efficiency and reduces errors because
of t he reusability of a code. O nce we create a function, we
can call it anywher e and anytime. T hebenefit of using a
function is reusability and modularity.
■■■■■: Python
Intr oduction
P yt hon
Functions
The
fun ction isa blo ckof cod edefine d witha
name .
We
use
f u nc tio n s
whe never
we
need
to
per fo rm
t he
sa me
task
multi p le
times
without
writing
t he
same
co de
agai n
.
It
can
take
arguments
and
returns
the
val ue
.
Python has a DRYprinciple like
other programming languages. DRY
stands for Don
t RepeatYourself.
Function improves efficiency and reduces errors because
of t he reusability of a code. O nce we create a function, we
can call it anywher e and anytime. T hebenefit of using a
function is reusability and modularity.
Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
P y tho n su p p orttwotype sof fun ctio n s
Buil t
-
infunc tio n
User
-
defined func tio n
The func tio ns whic h are co me al o ng withP y tho n itsel fare cal leda
buil t
-
in
func tio n
or
predefined func tio n. So me o f them areli sted belo w
.
Buil t
-
in
fun ctio n
range()
,
id()
,
type()
,
input()
,
eval
()
etc
■■■■■: Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
P y tho n su p p orttwotype sof fun ctio n s
Buil t
-
infunc tio n
User
-
defined func tio n
The func tio ns whic h are co me al o ng withP y tho n itsel fare cal leda
buil t
-
in
func tio n
or
predefined func tio n. So me o f them areli sted belo w
.
Buil t
-
in
fun ctio n
range()
,
id()
,
type()
,
input()
,
eval
()
etc
Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
Use r
-
d efined
fun ction
Funct i ons whi ch are created by programmer ex pl i cit lyaccordi ng to t he
requi rement are cal l eda u ser
-
def i ned f un cti on .
Creatin g a
Fu nctio n
Use thefol low ing steps to
to
defin e a fu nctio nin Pytho n.
Use the
def
keyw ord w iththe function name to define a function.
■■■■■: Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
Use r
-
d efined
fun ction
Funct i ons whi ch are created by programmer ex pl i cit lyaccordi ng to t he
requi rement are cal l eda u ser
-
def i ned f un cti on .
Creatin g a
Fu nctio n
Use thefol low ing steps to
to
defin e a fu nctio nin Pytho n.
Use the
def
keyw ord w iththe function name to define a function.
Use r
-
d efined
fun ction
Syntax of crea ting a function
function_ na m e
: Functionnamei sthenameofthefunction.We cangi veany nametofunction.
parameter
: Par ameter i stheval uepassedtothefuncti on. Wecanpassany number ofpar ameter s.Functi on
body usesthepar ameter
function_ bo d y
: Thefuncti onbody i sabl ockofcodethatper for mssometask. Thi sbl ockofcodei snothi ng
buttheacti onyou w antedtoaccompl i sh.
return value
: Retur nvaluei stheoutputofthefunction
.
def
function_name
(
parameter
1
,
parameter
2
):
# function body
# write someaction
return
value
Note:
W hiledef iningaf unc t ion,we us et wok eywords ,
def
(mandatory)and
return
(opt ional).
■■■■■: Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
Use r
-
d efined
fun ction
Syntax of crea ting a function
function_ na m e
: Functionnamei sthenameofthefunction.We cangi veany nametofunction.
parameter
: Par ameter i stheval uepassedtothefuncti on. Wecanpassany number ofpar ameter s.Functi on
body usesthepar ameter
function_ bo d y
: Thefuncti onbody i sabl ockofcodethatper for mssometask. Thi sbl ockofcodei snothi ng
buttheacti onyou w antedtoaccompl i sh.
return value
: Retur nvaluei stheoutputofthefunction
.
def
function_name
(
parameter
1
,
parameter
2
):
# function body
# write someaction
return
value
Note:
W hiledef iningaf unc t ion,we us et wok eywords ,
def
(mandatory)and
return
(opt ional).
Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
Us er
-
defined
function
■■■■■: Python
Intr oduction
P yt hon
Functions
Types of
Fu nc tions
Us er
-
defined
function
Us er
-
defined
function
# functio n
def
cal c ulato r(a, b):
add = a + b
# return the additi o n
return add
# cal lfunc tio n
# takereturn val ue invariable
res = cal c ulato r(
20
,
5
)
print("Additi o n :", res)
# Output A dditi o n :
25
■■■■■: Python
Intr oduction
P yt hon
Functions
Us er
-
defined
function
# functio n
def
cal c ulato r(a, b):
add = a + b
# return the additi o n
return add
# cal lfunc tio n
# takereturn val ue invariable
res = cal c ulato r(
20
,
5
)
print("Additi o n :", res)
# Output A dditi o n :
25
Python
Intr oduction
P yt hon
Functions
Call in ga fu nction
Us er
-
defined
function
Once w edefined a function or finalized structure, w ecan call that function by using its name.
We can also call that function from another function or program by importing it.
#fun ct ion
def
even_odd
(n):
# ch ec k
numn e
r is
evenor odd
if n%
2
==
0
:
pr int ('Evennumb er ')
el se :
pr int ('OddNumber ')
#call ingfunct ionby it sname
even_odd
(
19
)
#Out put Odd Number
■■■■■: Python
Intr oduction
P yt hon
Functions
Call in ga fu nction
Us er
-
defined
function
Once w edefined a function or finalized structure, w ecan call that function by using its name.
We can also call that function from another function or program by importing it.
#fun ct ion
def
even_odd
(n):
# ch ec k
numn e
r is
evenor odd
if n%
2
==
0
:
pr int ('Evennumb er ')
el se :
pr int ('OddNumber ')
#call ingfunct ionby it sname
even_odd
(
19
)
#Out put Odd Number
Python
Intr oduction
P yt hon
Functions
Us er
-
defined
function
First , we need to use t he i mport statement to i mport aspecif i c fun cti onf rom amodul e.
■■■■■: Python
Intr oduction
P yt hon
Functions
Us er
-
defined
function
First , we need to use t he i mport statement to i mport aspecif i c fun cti onf rom amodul e.