Unit – 2
Decision Control Statements
Introduction to DCS :
A Control Statement is a statement that determine the control flow of a set of instructions.
A Control statement can either comprise of one or more instructions.
The three fundamentals methods of control flow a programming language are sequential, selection and iterative control.
Decision Control Statements
The decision control statements usually jumps from one part of the code to another depending on whether a particular condition is satisfied or not .
They allow you to execute statements selectively based on certain decision. Such type of decision control statements are known as selection control statements or conditional branching statements.
a) if statement Nested if statement
b) if – else statement if – elif - else statement
Syntax of if Statement
iftest_expression :
print ( x) |
O / P : x = 11 |
|
Eg: age = int (input ( “Enter the age : “ )) |
If (age > = 18 ) : |
Print (“You are eligible to vote ) |
O/ P : Enter the age : 35 |
You are eligible to vote |
Eg :char = input (“Press any key : “) |
if (char .isalpha()); |
print(“The user has entered a character”) |
if(char.isdigit()); |
print(“The user has entered a digit “) |
if(char.isspace()); |
print(“The user entered a write space characters”) |
O/P : Press any key : 7 |
The user has entered a digit. |
if –else statement
print(“You are eligible to vote”) |
else |
yrs =18 – age |
print(“You have to wait for another “ + str/yrs “years to cast your vote”) |
O/P : Enter the age = 10 |
You have to wait for another 8 years to cast your vote |
|
Eg. a =int (input(“Enter the value of a:”)) |
b=int (input(“Enter the value of b:”)) |
if(a<b): |
large =a |
else: |
Nested if statements
Eg. num=int(input(“Enter any no from o-30”)) |
If(num>=0 and num<10): |
print(“if is in the range 0-10”) |
If(num>=10 and num<20): |
print(“It is an the range 10-20”) |
If(num>=20 and num<30) |
Print(“It is in the range 20-30”) |
if-elif-else statement
Systax :
Eg: num = int (input(“Enter any numbers”)) |
if(num = = 0): |
print(“The value is equal to zero”) |
elif(num>0): |
print(“The number is positive”) |
else : |
print(“The number is negative”) |
Iterative statements are decision control statements that are used to repeat the execution of a list of statements.
Python languages support two types of iterative statement – while loop & for loop .
While Loop
The while loop provides a mechanism to repeat one or more statements while a particularcondition is True .
Syntax :
print(c,end = ) |
|
i = i + 1 |
O/P : 0 1 2 3 4 5 6 7 8 9 10 |
|
Eg. m=int(input(“Enter the value of m : “)) |
n =int(input(“Enter the value of n : “)) |
s = 0 |
while(m< = n) |
s = s + m |
m = n + 1 |
print(“Sum =”,s) |
O/P : Enter the value of m : 3 |
Enter the value of n : 9 |
Sum = 42 |
For Loop
The range () function
Therange() function is a built in function inPython that is used to iterate over a sequence of numbers.The Syntax of range() is
Range( beg, end,[step])
The range() produces a sequence of numbers statement with beg(inclusive) and ending with one less than the number end.The step argument is optional.
By default every number in the range is increment by 1.but we can specify a different using step.
It can be both –ve& +ve , but not zero.
Eg. for i in range(1,5): for i in range(1,10,2):
print(i,,end =” “) print(i,,end =” “)
O/P : 1 2 3 4 O/P 1 2 5 7 9
Key Points to remembers
a) If range function is given a single argument , it produce an object with values from 0 to argument -1
For example : range( 10) is equal to writing range (o,10)
b) If range() is called with 2 arguments , it produces values from the fist to second .
For example : range(0,10)
c) If range() has interval of the sequence produced .In this case the 3rd argument must be an integer
For example : range(1 ,20 ,3)
for i in range(10): for i in range(1,15)
print(i,end = ‘ ‘) print( i , end= ‘ ‘)
O/P 0 1 2 3 4 5 6 7 8 9 O/P : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
for i in range(1,20,3):
print(I,code=’ ‘)
O/P : 1 4 7 10 13 16 19
Selecting an appropriate loop
Loop can be of different types such as entry controlled (also known as pre_test),exit –control (also known as post-test).counter controlled,and condition controlled (or sequential-control) loops.
Nested Loop :Loops that can be palced inside other loops Eg.WAP to print followingpattern
Pass 1 – 1 2 3 4 5 |
Pass 2 – 1 2 3 4 5 |
Pass 3 – 1 2 3 4 5 |
Pass 4 – 1 2 3 4 5 |
Pass 5 – 1 2 3 4 5
|
for i in range(1,6): |
print(“Pass,i,”_”,end =” “) |
for j in range(1,6): |
print(j,end=” “) |
print() |
The break statement |
d) The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. |
e) The break statement is widely used with for loop and while loop. |
Program :i = 1 |
while i<=10 |
print(i,end =” “) |
if i = = 5; |
break |
i = i +1 |
print(“\n Done”) |
O/P : 1 2 3 4 5 |
|
Hence the break statement is used to exit a loop from any point within.itsbody,bypassing its normal terminal expression.
When the break statement is encountered inside a loop,the immediately terminated and program control is passed to the next statement following the loop.
The continue Statement
The continue statement can entry apper in the body of a loop.
When the compiler encounter a continue statement, than the rest of statement in the loop are skipped and the control is unconditionally transferred to the loop-continationposition of the nearest enclosing loop.
Example :for i in range (1,11):
if(i = =5)
continue
print(i,end=” “ )
print(“\n Done”)
O/P : 1 2 3 4 5 6 7 8 9 10
|
The Continue statement is somewhat the appear of the break statement.
It forces the next iteration od the loop to test place,skipping any code in between and its test condition of the loop.
The Pass Statement
The pass statement is used when a statement is required syntacally but no command or code has to be executed.
It specifies a null operation or simply No Operation (NOP) statement.
Example : for letter in “HELLO” :
pass # The statement is doing nothing
print(“Pass .”,letter)
print(“Done”)
O/P : Pass : H
Pass : E
Pass : L
Pass : L
Pass : O
The pass statement is used as a placeholder .
Difference between comment and pass statements.
In Python programming pass is a null statements.The difference between a comment and pass statement is that while the interpreter lgnores a comment entirrly,passisnot ignored.
Comment is not executed but pass statement is executed but nothing happens.
7) The else statement used with Loops
In Python you can have the else statement associated with a loop statements.
If else statement is used with a for loop the else statement is executed hen the loop has compiled iterating.
But hen used with the while loop,the else statement is executed when the condition becomes false.
- The main difference between list and tuple is that you can chage the values in a list but next in atuple.This means that while tuple is a read only data type ,the list is not.
Example :Tup = (‘a’ , ‘bc’ , 78,1.23)
Tup2 –(‘d’ , 78)
print(Tup)
print(Tup[a]) # Prints first element of the tuple
print(Tup[1:3]) # Prints elements from 2nd till 3rd
print(Tup[2:]) # Prints 3rd element of the tuple
print(Tup * 2) # Repeats the tuple
print(Tup + Tup2) # Concatenates two tuples.
O/P : |
(‘a’ , ‘bc’ ,78 ,1.23) |
a |
(‘bc’ , 78 ) |
(78 , 1.23) |
(‘a’, ‘bc’ , 78, 1.23, ‘a’ , ‘ bc’ ,78,1.23) |
(‘a’, ‘bc’,78,1.23, ‘a’ ,78) |
Lists
a) A list consist of items separated by commas and enclosed within square brackets [ ]
b) For C,C++,or Java programmers lista are similar to arrays.
c) The only difference in an array and list is tha while array continue values of same data tyoes a list on the other hand,can have values belonging to different types.
d) The values started in a list are accessed using indexes .
e) The index of the first element is O and that of the the last element is n-1 ,where n is the total no. of elements is the list.
Ex)
list = [‘a’ ,’bc’,’78’,1.23] |
list2=[‘d’ ,78] |
print(list) |
print(list[0]) # Prints 1st element of the list |
print(list[1:3]) |
print(list[2:]) |
print(list * 2) |
print(list + list2) |
O/P : |
[‘a’ ,’bc’,’78’,1.23] |
a |
[‘a’ ,’bc’,’78’,1.23,‘a’ ,’bc’,’78’,1.23] |
[‘a’ ,’bc’,’78’,1.23,‘d’ ,78] |
Dictionary
a) Python dictionaries stores data in key-value pass
b) The key values are useally strings and value can be of any data type.
c) The key value passes are enclosed with curly braces{}
d) Each key-value pass is separated from the other using a colon (: ) .To access any value in the dictionary you just need to specify its key in square braces([ ]).
Ex)
Dict ={ “Item” , “Chocolate” , “Price” ,100}
print(Dict[“Item”])
print(Dict[“Price”])
O/P : Chocolate
100
Reference Books
- R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
- Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
- Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
- Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
- Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810