Lecture55 - 30272 - Control Structure 1
Lecture55 - 30272 - Control Structure 1
Control
if…else
for Loop
while
loop
Break and
continue Pass
statement
if...els
e⚫ Decision making is required when we want
to execute a code only if a certain condition
is satisfied.
⚫ The if…elif…else statement is used in
Python for decision making.
⚫ Logic:
⚫ if a year is not divisible by 4, its not a leap year.
⚫ If a year is divisible by 4 and not divisible by 100, it’s a
leap year.
⚫ If a year is divisible by 4 and 100 then it should be
divisible by 400
to be a leap year
Loop
s⚫Loops are used in
programming to repeat a
specific block of code.
⚫ Looping Constructs in
Python
◦ while
◦ for
While
loop
⚫ The while loop in Python is used to
iterate over a block of code as long as
the test expression (condition) is true.
⚫ We generally use this loop when we
don't know beforehand, the number of
times to iterate.
⚫ Write
a program to print the
number of digits of a given
number using while loop.
For
loop
⚫ For loops iterate over a given
sequence.
⚫ If
a number is divisible by any
number between 2 and n-1, its
not prime, otherwise prime
continue
statement
⚫ The continue statement is used to skip the
rest of the code inside a loop for the current
iteration only. Loop does not terminate but
continues on with the next iteration.
for loop with
else
⚫ A for loop can have an optional else block as
well. The else part is executed if the items in
the sequence used in for loop exhausts.
⚫ break statement can be used to stop a for
loop. In such case, the else part is ignored.
⚫ Hence, a for loop's else part runs if no break
occurs.
for loop with
else
Nested
Loop
while loop with
else
⚫ Same as that of for loop, we can
have an optional else block with
while loop as well.
Pass
statement
⚫ Suppose we have a loop or a function that
is not implemented yet, but we want to
implement it in the future.
⚫ They cannot have an empty body.
⚫ We use the pass statement to construct a
body that does nothing.