Control Structures
Control Structures
Control Structures:
Types of Constructs :
1) Sequential : All the statements written in a program gets executed one after the other in a
sequential manner.
Selection Statements :
i) if Statement :
Syntax : if condition :
statement(s)
else :
statement(s)
Statement(s) written in if part gets executed if the condition evaluates to true and the
statement(s) written in else part gets executed if the condition evaluates to false.
ii) if - elif -- else statement : is used when there is a need to check another condition in case the
test condition of if evaluates to false
.e.g. To find the grade of a student on the basis of percentage obtained.
To display dayname on the basis of day number.
Program
Program : Read two numbers and an arithmetic operator and display the
computed result.
Iteration :
Iteration statements allow a set of statements to be performed repeatedly until a
certain condition is fulfilled.
or Iteration statements (loop) are used to execute a block of statements as long as
the condition is true.
Types of loops:
1) for (2) while
range( ) function : contains three arguments i.e. starting value, ending value and
step value. By default step value is 1.
e.g. range( 1 , n):
will produce a list having values starting from 1,2,3… upto n-1.
Last value is one less than the specified end value.
range(1,9,2) : step value is 2. Values are 1,3,5,7.
for loop : A for loop is used to repeatedly execute a statement or a set of statements
based on a condition. The loop terminates when the condition becomes false. A for
loop is considered deterministic because it is typically used for a fixed number of
iterations or repetitions
Syntax:
for val in range() :
statements
e.g.
Program to display even numbers and their sum in the range of 1 to 20.
sum = 0
for x in range(2,21,2) :
print(x)
sum = sum + x
print("Sum of even numbers = ", sum)
Output:
2
4
6
8
.
.
20
Sum of even numbers = 110
e.g. program to display the odd numbers and their sum in the range of 1 to 20.
sum = 0
num = 1
while num < 20 :
print(num)
sum = sum + num
num = num + 2
print(“Sum of odd numbers =”, sum)