0% found this document useful (0 votes)
14 views

Chap 6 Python

The document discusses various control structures in Python including sequential, alternative/branching, and iterative/looping structures. It covers the syntax and use of simple if statements, if/else statements, nested if/elif/else statements, while loops, and for loops. Examples are provided to demonstrate each structure.

Uploaded by

vtpvmcsca2021
Copyright
© © All Rights Reserved
0% found this document useful (0 votes)
14 views

Chap 6 Python

The document discusses various control structures in Python including sequential, alternative/branching, and iterative/looping structures. It covers the syntax and use of simple if statements, if/else statements, nested if/elif/else statements, while loops, and for loops. Examples are provided to demonstrate each structure.

Uploaded by

vtpvmcsca2021
Copyright
© © All Rights Reserved
You are on page 1/ 50

6.

CONTROL STRUCTURES
LEARNING OBJECTIVES

• 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.
Fundamental Control
Structures
• In general, statements in the programs are executed
sequentially, that is the statements are executed one
after another. This is called Sequencing
• Some times 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. This is called Alternative or Branching.
• We may need to execute a set of statements multiple
times, called Iteration or Looping
Control Structures
• A program statement that causes a jump of control
from one part of the program to another is called
control structure or control statement
• There are three types of Control structures

•Sequential
•Alternative Or Branching
•Iterative or Looping
Sequential Statement

• A Sequential statement is composed of a


sequence of statements which are
executed one after another
Examples :
• Printing the bio data
• Finding total ,average for student’s mark
• Calculating measurements (area, perimeter) to any
shapes
Sequential Statement

# Program to print your name and address - example for


sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")

Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN
Sequential Statement

# Program to find the area of circle


r=int(input(“Enter the radius value”))
Area = 3.14 * (r**2)
print(“The area of circle is “, Area)

Output:
Enter the radius value 8
The area of circle is 200.96
Alternative or
Branching Statement

• In our day-to-day life we need to take various


decisions and choose an alternate path to achieve
our goal
• In the programs the control flow will take the true
path based on the criteria
• This type of decision making is what we are to learn
through alternative or branching statement.
Examples
Finding odd or even
Checking positive or negative
Types of Alternative or
Branching statements
Simple if statement

if….else statement

if….elif statement
Simple if statement

• Simple if is the simplest of all


decision making statements.
• Condition should be in the form of
relational or logical expression.
Simple if statement

• In the above syntax if the condition is true


statements - block 1 will be executed

• The Python program does not check the alternative


process when the condition is failed
EXAMPLES

x=int (input("Enter your age :"))


if x>=18: Enter your age : 54
print ("You are eligible for You are eligible for voting
voting")

y=int(input(“Enter number”))
if y > 0 : Enter number : - 4
print( “The given number is >>>
positive”)
if..else statement

• The if .. else statement provides control to check the


true block as well as the false block
• if..else statement provides two possibilities and the
condition determines which BLOCK is to be
executed.
• The following is the syntax of if…else statement
if..else statement
EXAMPLES
a = int(input("Enter any number :"))
if a%2==0:
print (a, " is an even number")
else:
print (a, " is an odd number")
Output 1:
Enter any number :56
56 is an even number

Output 2:
Enter any number :67
67 is an odd number
if..else statement
• An alternate method to write the if..else program is
also available in Python.
• The complete if..else can also written as

• The condition specified in the if is checked, if it is


true, the value of variable1 is stored in variable on
the left side of the assignment, otherwise variable2 is
if..else statement

# Program to find the given number is odd or even


a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
print (a, " is ",x)
Output 1:
Enter any number :3
3 is odd

Output 2:
Enter any number :22
22 is even
Nested if..elif...else statement:

• When we need to construct a chain of if statement(s)


then ‘elif’ clause can be used instead of ‘else’.
• SYNTAX
if < condition-1> :
Statements-Block1
elif<condition -2>:
Statements-Block2
else:
Statements-Blockn
Nested if..elif...else statement:

• In the syntax of if..elif..else


condition-1 is tested if it is
true then statements-
block1 is executed,
• otherwise the control
checks condition-2, if it is
true statements-block2 is
executed
• If all the conditions fail
statements-block n
mentioned in else part is
executed.
Nested if..elif...else statement:
Nested if..elif...else statement:

• ‘elif’ clause combines if..else-if..else statements to


one if..elif…else.
• ‘elif’ can be considered to be abbreviation of ‘else
if’.
• In an ‘if’ statement there is no limit of ‘elif’ clause
that can be used, but an ‘else’ clause if used should
be placed at the end
• if..elif..else statement is similar to nested if
statement
EXAMPLE – Nested if

m1=int (input(“Enter mark in first subject : ”))


m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80: Output 1:
print (“Grade : A”) Enter mark in first subject : 34
Enter mark in second subject : 78
elif avg>=70 and avg<80: Grade : D
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”) Output 1:
Enter mark in first subject : 34
elif avg>=50 and avg<60: Enter mark in second subject :15
print (“Grade : D”) Grade : E
else:
the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a or b or c’)
Output 2:
Output 1:
Enter a character : S
Enter a character : U
S , the letter is not a or b or c
U is a vowel
Iteration or Looping constructs

• Iteration or loop are used in situation when the user


need to execute a block of code several of times or
till the condition is satisfied.
• A loop statement allows to execute a statement or
group of statements multiple times
• Python provides two types of looping constructs:
1. while loop
2. for loop
while loop

• Syntax of while loop


while < condition> : Boolean Express

Statements-Block1
[else : Optional part

Statements-Block2]
While loop -
Flow diagram
• In the while loop, the condition is any valid Boolean
expression returning True or False.
• The else part of while is optional part of while.
• The statements block1 is kept executed till the
condition is True.
• If the else part is written, it is executed when the
condition is tested False.
• while loop belongs to entry check loop type, that is
it is not executed even once if the condition is
tested False in the beginning.
EXAMPLE –WHILE LOOP

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable

Output:
10 11 12 13 14 15
Value of i when the loop exit 16
PARAMETERS OF print()

• print() function can have end, sep as parameters.

• end parameter can be used when we need to give


any escape sequences like ‘\t’ for tab, ‘\n’ for new
line and so on.

• sep as parameter can be used to specify any special


characters like, (comma) ; (semicolon) as separator
between values
while loop - with else part

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
else:
print ("\nValue of i when the loop exit ",i)

Output:
10 11 12 13 14 15
FOR LOOP
• 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) is executed if it
is only True otherwise the loop is not executed.
• SYNTAX
for counter_variable in sequence:
Statements-Block1
[else : # optional part
Statements-Block2]
Importance of range()

• The counter_variable mentioned in the syntax is


similar to the control variable
• The 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.
Importance of range()

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.
Examples for range()
range (1,30,1) will start the range of values from 1 and end at 29
range (2,30,2) will start the range of values from 2 and end at 28
range (30,3,-3) will start the range of values from 30 and end at 6
range (20) will consider this value 20 as the end value(or upper limit)
and starts the range count from 0 to 19 (remember always range() will
work till stop -1 value only)
FOR LOOP - EXAMPLES

1) # Printing even numbers


for i in range (2,10,2): Output:
2468
print (i, end=' ')

2) # Printing odd numbers


Output:
for i in range(1,10,2):
13579
print (i,end=' ') End of the loop
else:
print ("\nEnd of the loop")
FOR LOOP - EXAMPLES

3)# Finding sum of numbers


n = 100 Output:
sum = 0 Sum of 1 until 100: 5050
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum))

4) # use of string in range()


for word in 'Computer': Output:
print (word,end=' ') Computer
else: End of the loop
print ("\nEnd of the loop")
Nested loop structure
• 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.
EXAMPLE – NESTED LOOP Output:
i=1 1
while (i<=6):
12
for j in range (1,i):
print (j,end='\t') 123
print (end='\n') 1234
i +=1 12345
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
FLOW DIAGRAM OF BREAK
AND CONTINUE STATEMENTS
break statement
• The break statement terminates the loop containing it.
• Control of the program flows to the statement
immediately after the body of the loop.
• A while or for loop will iterate till the condition is tested
false, but one can even transfer the control out of the
loop (terminate) with help of break statement.
• When the break statement is executed, the control
flow of the program comes out of the loop and starts
executing the segment of code after the loop structure.
• If break statement is inside a nested loop (loop inside
another loop), break will terminate the innermost loop.
break statement
Working of break statement

• The working of break statement in for loop and while loop


for var in sequence:
if condition:
break
#code inside for loop
#code outside for loop
while test expression:
if condition:
break
#code inside while loop
#code outside while loop
break – Examples
1 2
for word in “Coffee” : for word in “Jump Statement”:
if word == “e”: if word = = “e”:
break break
print (word, end=”)
print (word, end= '
else:
')
print (“End of the loop”)
print (“\n End of
theprogram”)
Output: Output:
Coff Jump Stat
End of the program
continue statement
• Continue statement is used to skip the remaining
part of a loop and start with next iteration.
• Continue statement forces the next iteration
skipping any part in the iteration

• SYNTAX
continue
Working of
continue statement
• The working of break statement in for loop and while loop
for var in sequence:
if condition:
continue
#code inside for loop
#code outside for loop
while test expression:
if condition:
continue
#code inside while loop
#code outside while loop
continue - Examples

for word in “Computer”:


if word == “e”:
continue
print (word, end=”)
print (“\n End of the program”)

Output:
Computr
End of the program
pass statement
• 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.
• pass statement can be used in ‘if’ clause as well as
within loop construct, when you do not want any
statements or commands within that block to be
executed
pass statement

• SYNTAX
pass
a=int (input(“Enter any number :”))
if (a==0): Output:
pass Enter any number :3
else: non zero value is accepted
print (“non zero value is accepted”)

if the input value is 0 (zero) then no action will be


performed, for all the other input values the
above output will be displayed
Pass statement

• pass statement is generally used as a placeholder.


• When we have a loop or function that is to be
implemented in the future and not now, we cannot
develop such functions or loops with empty body
segment because the interpreter would raise an
error.
• So, to avoid this we can use pass statement to
construct a body that does nothing

You might also like