Chapter - 4 Control Structures
Chapter - 4 Control Structures
Control Structures
Conditional and looping constructs
Introduction
Tools that help in better understanding of the problem
statement and decisions to be made accordingly are:
1. Flow charts
2. Pseudo code
3. Decision tree
Flow charts
It is the pictorial representation of the sequence of steps and
decisions needed to perform a task.
Flow chart depicts the “flow” of a program.
Commonly used symbols in flow chart
Symbol Name
Start/Stop
Process
Input/Output
Decision
1. Sequence
2. Selection/Decision
3. Iteration/Loop
Program Control Flow
1. Sequence
The statements in the programs are executed in
an order one line at a time from the top to the bottom
of your program.
2. Selection/Decision
The set of statements are executed based on the
condition and then change the course of program.
3. Iteration/Loop
Loops are used to repeatedly execute the same
statement(s) in a program.
1. Sequence
2. Selection
(Decision making)
There are four types of decision-making statements in
python:
a. if statement
b. if-else statement
c. if-elif-else statement
d. Nested if-else statement
2. Selection (Decision making)
a. if statement
Syntax:
if condition:
statement(s)
e.g.
if x > 0:
print (“x is positive”)
2. Selection (Decision making)
b. if-else statement
e.g.
if age >= 18:
print (“Can Vote”)
else:
print (“Can’t Vote”)
2. Selection (Decision making)
c. if-elif-else statement
Example:
num=int(input("Enter number"))
if (num>=0):
if (num==0):
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
3. Iteration
Loops are used to repeatedly execute the same code
in a program.
a) while loop
b) for loop
3. Iteration
a) while loop
Example
a loop to print nos. from 1 to 10
i=1
while (i <=10):
print (i, end=‘ ‘)
i = i+1
while Loop with else
e.g.
x=1
while(x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)
Output:
inside while loop value of x is 1
inside while loop value of x is 2
inside else value of x is 3
Nested while loop
Block of statement belonging to while can have
another while statement, i.e. a while can
contain another while.
e.g.
i=1
while(i<=3):
j=1
while(j<=i):
print(j, end=" ") # inner while loop
j=j+1 Output:
print("\n") 1
i=i+1 1 2
1 2 3
3. Iteration
b) for loop
Output: 12345678910
Example 1:
for letter in "Python":
print("Current letter", letter)
else:
print("End of loop")
Example 2:
num=[10,20,30,40,50]
for i in num:
print(i)
Nested for
Break can be used in while loop and for loop. Break is mostly
required,
when because of some external condition, we need to exit
from a loop.
Example
Output:
for letter in "Python": >>>
if (letter == "h"): P
break y
print(letter) t
Continue Statement
This statement is used to tell Python to skip the rest of the
statements of the current loop block and to move to next
iteration, of the loop.