CHAPTER 6
Control
Structures
• To gain knowledge on the various
flow of control in Python language.
• To learn through the syntax how
to use conditional construct to
improve the efficiency of the
program flow.
• To apply iteration structures to
develop code to repeat the program
segment for specific number of
times or till the condition is
satisfied.
• Programs may contain set
of statements.
• These statements are the
executable segments that
yield the result.
• In general, statements are
executed sequentially, that
• There may be situations
in our real life
programming where we
need to skip a segment
or set of statements
and execute another
segment based on the
test of a condition.
• Also, we may need to
execute a set of
statements multiple
times, called iteration
or looping.
• In this chapter we are
to focus on the various
Control
Structures
A program
statement that
causes a jump of
control from one
part of the
program to
Sequentia
l
A sequential
statement is
composed of a
sequence of
statements
Alternative
or
Branching
Statement
• Simple if
statement
• if..else
statement
Simple if
statemen
Simple if is the
simplest of all
decision making
statements.
Condition should
be in the form of
yntax
if <condition>:
statements-
block1
x=int (input("Enter
your age :"))
if x>=18:
print("You are
eligible for voting")
xample
if..else
statemen
yntax
if <condition>:
statements-
block1
else:
statements-
x=int (input("Enter
your age :"))
if x>=18:
print("You are
eligible for voting")
else:
xample
An alternate
method to rewrite
the above program
is also available in
Python.
The complete
yntax
variable = variable1 if
condition else variable 2
a = int (input("Enter
any number :"))
x="even" if a%2==0
else "odd"
print (a, " is ",x)
xample
Output 1:
Enter any number :3
3 is odd
Output 2:
Enter any number :22
22 is even
Nested
if..elif...els
e
yntax
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
m1=int(input("Enter mark in first subject:
m2=int(input("Enter mark in second subje
avg=(m1+m2)/2
if avg>=80:
print ("Grade : A")
elif avg>=70 and avg<80:
print ("Grade : B")
elif avg>=60 and avg<70:
print ("Grade : C")
elif avg>=50 and avg<60:
print ("Grade : D")
else:
print ("Grade : E")
Example
Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
Output 2 :
Enter mark in first subject : 67
Enter mark in second subject : 73
Grade : B
Iteration or
Looping
constructs
A loop statement
allows to execute a
statement or group
of statements
multiple times.
Python provides
two types of
looping constructs:
• while loop
• for loop
while loop
yntax
while <condition>:
statements block 1
[else:
statements block2]
i = 1
while i < 15:
print(i)
i += 1
Example
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
x = 0
while (x < 16):
print(x)
x += 1
else:
print("nValue of i when the loop exit ",x)
Example
Output: 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Value of i when the loop exit 16
for
for loop is the most
comfortable loop.
It is also an entry check
loop.
The condition is checked
in the beginning and the
body of the
loop(statements-block 1)
for counter_variable in sequence:
statements-block 1
[else: #
optional block
statements-block 2]
yntax
The counter_variable mentioned in the
syntax is similar to the control variable
that we used in the for loop of C++
sequence refers to the initial, final and
increment value.
for loop uses the range() function in the
sequence to specify the initial, final and
increment values. range() generates a
list of values starting from start till
stop-1.
The syntax of range() is as follows:
range (start,stop,[step])
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value,
this is optional part.
range(n): generates a
set of whole numbers
starting from 0 to (n-1).
for i in range (2,10,2):
print (i, end=' ')
Output:
2 4 6 8
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
output: apple, banana
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
Exampl
e
output: apple
Therange()function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
for x in range(6):
print(x)
Example
OUTPUT
0
1
2
3
4
5
Therange()function defaults to 0 as a
starting value, however it is possible to
specify the starting value by adding a
parameter:range(2, 6), which means
values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)
Example
OUTPUT
2
3
4
5
Therange()function defaults to increment
the sequence by 1, however it is possible to
specify the increment value by adding a third
parameter:range(2, 30,3):
for x in range(2, 30, 3):
print(x)
Example
OUTPUT
2
5
8
11
14
17
20
23
26
29
for x in range(6):
print(x)
else:
print("Finally finished!")
OUTPUT
0
1
2
3
4
5
Finally finished!
Example
for i in range (2,10,2):
print (i, end=' ')
for i in range(2,10,2):
print (i,end=' ')
else:
print ("nEnd of the loop")
n = 10
sum = 0
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum))
Example
for word in 'Computer':
print (word,end=' ')
else:
print ("nEnd of the loop")
Example
Nested
loop
A loop placed within another
loop is called as nested loop
structure.
One can place
• a while within another while;
• for within another for;
• for within while and
• while within for to construct
such nested loops.
i=1
while (i<=6):
for j in range (1,i):
print (j,end='t')
print (end='n')
i +=1
Example
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Jump
Statements
in Python
The jump statement in Python, is
used to unconditionally transfer the
control from one part of the
program to another.
There are three keywords to
achieve jump statements in Python:
break, continue, pass.
break
stateme
The break statement terminates
the loop containing it.
Control of the program flows to
the statement immediately after
the body of the loop.
yntax
break
Example
for letter in 'Python’:
if letter == 'h':
break
print ('Current Letter :',letter)
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")
Examp
OUTPUT
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
for word in "Jump
Statement":
if word == "e":
break
print (word, end= ' ')
Examp
for word in "Jump
Statement":
if word == "e":
break
print (word, end='')
else:
print("End of the loop")
Example
contin
ue
Continue statement
unlike the break
statement is used to skip
the remaining part of a
loop and start with next
iteration.
yntax
conti
Examp
for letter in 'Python’:
if letter == 'h':
continue
print ('Current Letter :',letter)
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :',
var)
print ("Good bye!")
Exampl
for word in "Jump
Statement":
if word == "e":
continue
print (word, end='')
else:
print("End of the loop")
print("n End of the
pass
stateme
yntax
pas
pass statement in Python programming
is a null statement.
pass statement when executed by the
interpreter it is completely ignored.
Nothing happens when pass is executed,
it results in no operation.
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Exampl
a=int (input("Enter any
number :"))
if (a==0):
pass
else:
print ("non zero value is
accepted")
Exampl
Hands on
Experience
Write a program to display
A
A B
A B C
A B C D
A B C D E
for i in range (65, 70):
for j in range (65, i + 1):
print (chr(j), end = ' ')
print (end='n')
i+=1
Using if..else..elif statement
write a suitable program to
display largest of 3 numbers.
a = int (input("Enter number 1"))
b = int (input("Enter number 2"))
c = int (input(" Enter number 3"))
if a > b and a > c:
print ("A is greatest")
elif b > a and b > c:
print ("B is greatest")
else:
print ("C is greatest")
for i in range (1, 100, 2):
print (i, end = " ")
Write a program to
display all 3 digit odd
numbers.
n = int (input("Enter the
number"))
for i in range (1,13):
print (n, "x", i, "= ", n * i)
Write a program to display
multiplication table for a given
number.
x = int (input("Enter a number"))
if x>0:
print (x, "is a positive number")
elif x < 0:
print (x, "is a negative
number")
else:
print (x, "is zero")
Thank you
Kalai

TN 12 computer Science - ppt CHAPTER-6.pptx

  • 1.
  • 2.
    • To gainknowledge on the various flow of control in Python language. • To learn through the syntax how to use conditional construct to improve the efficiency of the program flow. • To apply iteration structures to develop code to repeat the program segment for specific number of times or till the condition is satisfied.
  • 4.
    • Programs maycontain set of statements. • These statements are the executable segments that yield the result. • In general, statements are executed sequentially, that
  • 5.
    • There maybe situations in our real life programming where we need to skip a segment or set of statements and execute another segment based on the test of a condition.
  • 6.
    • Also, wemay need to execute a set of statements multiple times, called iteration or looping. • In this chapter we are to focus on the various
  • 7.
  • 8.
    A program statement that causesa jump of control from one part of the program to
  • 10.
  • 11.
    A sequential statement is composedof a sequence of statements
  • 12.
  • 13.
    • Simple if statement •if..else statement
  • 14.
  • 15.
    Simple if isthe simplest of all decision making statements. Condition should be in the form of
  • 16.
  • 17.
    x=int (input("Enter your age:")) if x>=18: print("You are eligible for voting") xample
  • 18.
  • 19.
  • 21.
    x=int (input("Enter your age:")) if x>=18: print("You are eligible for voting") else: xample
  • 22.
    An alternate method torewrite the above program is also available in Python. The complete
  • 23.
    yntax variable = variable1if condition else variable 2
  • 24.
    a = int(input("Enter any number :")) x="even" if a%2==0 else "odd" print (a, " is ",x) xample Output 1: Enter any number :3 3 is odd Output 2: Enter any number :22 22 is even
  • 25.
  • 26.
    yntax if <condition-1>: statements-block 1 elif<condition-2>: statements-block 2 else: statements-block n
  • 28.
    m1=int(input("Enter mark infirst subject: m2=int(input("Enter mark in second subje avg=(m1+m2)/2 if avg>=80: print ("Grade : A") elif avg>=70 and avg<80: print ("Grade : B") elif avg>=60 and avg<70: print ("Grade : C") elif avg>=50 and avg<60: print ("Grade : D") else: print ("Grade : E") Example Output 1: Enter mark in first subject : 34 Enter mark in second subject : 78 Grade : D Output 2 : Enter mark in first subject : 67 Enter mark in second subject : 73 Grade : B
  • 29.
  • 30.
    A loop statement allowsto execute a statement or group of statements multiple times.
  • 32.
    Python provides two typesof looping constructs: • while loop • for loop
  • 33.
  • 34.
    yntax while <condition>: statements block1 [else: statements block2]
  • 36.
    i = 1 whilei < 15: print(i) i += 1 Example Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 37.
    x = 0 while(x < 16): print(x) x += 1 else: print("nValue of i when the loop exit ",x) Example Output: 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Value of i when the loop exit 16
  • 38.
  • 39.
    for loop isthe most comfortable loop. It is also an entry check loop. The condition is checked in the beginning and the body of the loop(statements-block 1)
  • 40.
    for counter_variable insequence: statements-block 1 [else: # optional block statements-block 2] yntax
  • 41.
    The counter_variable mentionedin the syntax is similar to the control variable that we used in the for loop of C++ sequence refers to the initial, final and increment value. for loop uses the range() function in the sequence to specify the initial, final and increment values. range() generates a list of values starting from start till stop-1.
  • 42.
    The syntax ofrange() is as follows: range (start,stop,[step]) Where, start – refers to the initial value stop – refers to the final value step – refers to increment value, this is optional part.
  • 43.
    range(n): generates a setof whole numbers starting from 0 to (n-1).
  • 44.
    for i inrange (2,10,2): print (i, end=' ') Output: 2 4 6 8 Example
  • 45.
    fruits = ["apple","banana", "cherry"] for x in fruits: print(x) if x == "banana": break Example output: apple, banana
  • 46.
    fruits = ["apple","banana", "cherry"] for x in fruits: if x == "banana": break print(x) Exampl e output: apple
  • 47.
    Therange()function returns asequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
  • 48.
    for x inrange(6): print(x) Example OUTPUT 0 1 2 3 4 5
  • 49.
    Therange()function defaults to0 as a starting value, however it is possible to specify the starting value by adding a parameter:range(2, 6), which means values from 2 to 6 (but not including 6):
  • 50.
    for x inrange(2, 6): print(x) Example OUTPUT 2 3 4 5
  • 51.
    Therange()function defaults toincrement the sequence by 1, however it is possible to specify the increment value by adding a third parameter:range(2, 30,3):
  • 52.
    for x inrange(2, 30, 3): print(x) Example OUTPUT 2 5 8 11 14 17 20 23 26 29
  • 53.
    for x inrange(6): print(x) else: print("Finally finished!") OUTPUT 0 1 2 3 4 5 Finally finished! Example
  • 54.
    for i inrange (2,10,2): print (i, end=' ') for i in range(2,10,2): print (i,end=' ') else: print ("nEnd of the loop") n = 10 sum = 0 for counter in range(1,n+1): sum = sum + counter print("Sum of 1 until %d: %d" % (n,sum)) Example
  • 55.
    for word in'Computer': print (word,end=' ') else: print ("nEnd of the loop") Example
  • 56.
  • 57.
    A loop placedwithin another loop is called as nested loop structure. One can place • a while within another while; • for within another for; • for within while and • while within for to construct such nested loops.
  • 58.
    i=1 while (i<=6): for jin range (1,i): print (j,end='t') print (end='n') i +=1 Example
  • 59.
    1 1 2 1 23 1 2 3 4 1 2 3 4 5
  • 60.
  • 61.
    The jump statementin Python, is used to unconditionally transfer the control from one part of the program to another. There are three keywords to achieve jump statements in Python: break, continue, pass.
  • 63.
  • 64.
    The break statementterminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
  • 65.
  • 67.
    Example for letter in'Python’: if letter == 'h': break print ('Current Letter :',letter) OUTPUT: Current Letter : P Current Letter : y Current Letter : t
  • 68.
    var = 10 whilevar > 0: print ('Current variable value :', var) var = var -1 if var == 5: break print ("Good bye!") Examp OUTPUT Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye!
  • 69.
    for word in"Jump Statement": if word == "e": break print (word, end= ' ') Examp
  • 70.
    for word in"Jump Statement": if word == "e": break print (word, end='') else: print("End of the loop") Example
  • 71.
  • 72.
    Continue statement unlike thebreak statement is used to skip the remaining part of a loop and start with next iteration.
  • 73.
  • 75.
    Examp for letter in'Python’: if letter == 'h': continue print ('Current Letter :',letter) OUTPUT: Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n
  • 76.
    var = 10 whilevar > 0: var = var -1 if var == 5: continue print ('Current variable value :', var) print ("Good bye!") Exampl
  • 77.
    for word in"Jump Statement": if word == "e": continue print (word, end='') else: print("End of the loop") print("n End of the
  • 78.
  • 79.
  • 80.
    pass statement inPython programming is a null statement. pass statement when executed by the interpreter it is completely ignored. Nothing happens when pass is executed, it results in no operation.
  • 81.
    for letter in'Python': if letter == 'h': pass print ('This is pass block') print ('Current Letter :', letter) print ("Good bye!") Exampl
  • 82.
    a=int (input("Enter any number:")) if (a==0): pass else: print ("non zero value is accepted") Exampl
  • 83.
  • 84.
    Write a programto display A A B A B C A B C D A B C D E
  • 85.
    for i inrange (65, 70): for j in range (65, i + 1): print (chr(j), end = ' ') print (end='n') i+=1
  • 86.
    Using if..else..elif statement writea suitable program to display largest of 3 numbers.
  • 87.
    a = int(input("Enter number 1")) b = int (input("Enter number 2")) c = int (input(" Enter number 3")) if a > b and a > c: print ("A is greatest") elif b > a and b > c: print ("B is greatest") else: print ("C is greatest")
  • 88.
    for i inrange (1, 100, 2): print (i, end = " ") Write a program to display all 3 digit odd numbers.
  • 89.
    n = int(input("Enter the number")) for i in range (1,13): print (n, "x", i, "= ", n * i) Write a program to display multiplication table for a given number.
  • 90.
    x = int(input("Enter a number")) if x>0: print (x, "is a positive number") elif x < 0: print (x, "is a negative number") else: print (x, "is zero")
  • 91.