PPS NOTES Unit-2 (2024 Pattern)
PPS NOTES Unit-2 (2024 Pattern)
Statements
2.1Selection/conditional Statements:
Q. Explain selection/conditional statements with flowchart
• The selection control statements usually jump from one part of code to another
depending on whether a particular condition is satisfied or not.
• It allow us to execute statements selectively(branchwise)based on certain decisions.
• Python language supports different types of selection/conditional/branching
statements.
1. If statements
2. If.... else statements
3. If…elif….else statements
4. Nested if
2.1.1if
1. If statements:
• If statement is a simplest form of decision control statements that is frequently
used in decision making.
• If statements may include one statement or N statements enclosed within the if
block
• If the expression is true the statements of if block get executed, otherwise these
statements will be skipped and the execution will be jump to statement just outside
if block.
1
• Syntax:
if (expression/condition):
Block of statements
Statements outside if
• Flowchart:
✓ Example:
i = 10
# Checking if i is greater than 15
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output
I am Not in if
1
PPSUnit-II SKNSITS
2.1.2if-else
• In simple if statement, test expression is evaluated and if it is true the statements
in if block get executed, But if we want a separate statements to be get executed if
it returns false in this case we have to use if..else control statement.
• If else statement has two blocks of codes, each for if and else.
• The block of code inside if statement is executed if the expression in if statement
is TRUE, else the block of code inside else is executed.
• Syntax:
if (expression/condition):
Block of statements
else:
Block of statements
2
PPSUnit-II SKNSITS
• Flowchart:
✓ Example:
x=5
if (x<10):
print(“Condition is TRUE”)
else:
print(“Condition is FALSE”)
output:
Condition is TRUE'
Output
Condition is TRUE
i = 20
# Checking if i is greater than 0
if (i > 0):
print("i is positive")
else:
print("i is 0 or Negative")
Output
i is positive
3
2.1.3if-elif-else
• Python supports if..elif..else to test additional conditions apart from the initial test
expression.
• It work just like a if…else statement.
• The programmer can have as many elif statements/branches as he wants depending
on the expressions that have to be tested.
• A series of if..elif statements can have a final else block, which is called if none of
the if or elif expression is true.
• Syntax:
if (expression/condition):
Block of statements
4
PPSUnit-II SKNSITS
elif(expression/condition):
Block of statements
elif(expression/condition):
Block of statements
else:
Block of statements
• Flowchart:
Example:
x=5
if(x == 2):
print(“x is equal to2”)
elif(x<2):
print(“x is less than2”)
else:
print(“x is greater than2”)
Output:
X is greater than 2
5
i = 25
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output:
i is not present
6
PPSUnit-II SKNSITS
2.1.4nestedif
• A statement that contains other statements is called nested/compound statements.
• In nested if else statements, if statement is nested inside an if statements. So, the nested
if statements will be executed only if the expression of main if statement returns
TRUE.
• Syntax:
if (expression/condition):
if(expression/condition):
statements
else:
statements
else:
statements
• Flowchart
• Example
x=5
if (x<=10):
if(x==10):
print(“Number is Ten”)
else:
print(“Number is less than Ten”)
else:
print(“Number is greater than Ten”)
7
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
OUTPUT:
Above ten,
and also above 20!
8
PPSUnit-II SKNSITS
• Iterative statements are decision control statements that are used to repeat
the execution of a list of statements.
• Python language supports two types of statements while loop and for loop.
• As shown in the syntax above, in the while loop condition is first tested.
• If the condition is True, only then the statement block will be executed.
• Otherwise, if the condition is False the control will jump to statement y, that is the
immediate statement outside the while loop block.
• Flowchart:
9
PPSUnit-II SKNSITS
• Example:
Program to print numbers from 1 to 10.
Output:
Numbers from 1 to 10:
1 2 3 4 5 6 7 8 9 10
• Syntax:
For loop_control_var in sequence:
statement block1
Statement x
10
PPSUnit-II SKNSITS
• Flowchart:
• Example:.
Output: Output:
1234 13 579
The range() function is commonly used with for loops to generate a sequence of numbers. It can
take one, two, or three arguments:
• range(stop): Generates numbers from 0 to stop-1.
• range(start, stop): Generates numbers from start to stop-1.
• range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.
Output:
11
0
2
4
6
8
Python continue Statement returns the control to the beginning of the loop.
for i in 'geeksforgeeks':
if i == 'e' or i == 's':
continue
print(i)
Output:
for i in 'geeksforgeeks':
12
# break the loop as soon it sees 'e'
# or 's'
if i == 'e' or i == 's':
break
print(i)
Output:
E
# An empty loop
for i in 'geeksforgeeks':
pass
print(i)
Output
s
print(i)
print("No Break\n")
Output
2
13
3
No Break
• Loops can be of different types such as entry controlled (also known as pre-
test),exit controlled (also known as post-test), counter controlled and condition
controlled (or sentinel-controlled) loops.
14
PPSUnit-II SKNSITS
• If condition is not met in entry-controlled loop, then the loop will never execute.
• However, in case of post-test, the body of the loop is executed unconditionally for
the first time.
• If the requirement is to have a pre-test loop, then choose a for loop or a while loop.
• The table below shows comparison between Pre-test loop and post-test loop.
Feature Pre-test Loop Post-test Loop
Initialization 1 2
Number of tests N+1 N
Statements executed N N
Loop control variable update N N
Minimum Iterations 0 1
15
PPSUnit-II SKNSITS
2.3Nested loops
• Python allows its users to have a nested loop, that is,loops can be placed inside
another loop.
• This feature works with while as well as for loop.
• Nested loops are commonly used with for loop because it is easiest to control.
• Loops can be nested at any desired level.
• Loopsshouldbeproperlyindentedtoidentifywhichstatementsarecontainedwithin which
loop.
• Example:
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
16
Output
1 4
1 5
2 4
2 5
Output
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
3*1=3
3*2=6
17
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
print("*",end="")
print("\r")
Output
*
**
***
****
*****
18
PPSUnit-II SKNSITS
Example2:
last Number=6
for row in range(1, last Number):
for column in range(1,row+1):
print(column,end='')
print("")
Output
1
12
123
1234
12345
19
PPSUnit-II SKNSITS
• Example1(For‘ for loop’):Print numbers from 0 to10 and print a message when
the loop is ended.
for x in range(11):
print(x)
else:
print(“Loop is finished”)
• Example2(For‘while loop”):
i=1
while(i<0)
print(i)
i=i-1
else:
print(i,“is not negative so loop did not execute”)
Output:
20
PPSUnit-II SKNSITS
if(i=="c"):
break
print(i)
Output:
w
el
2.5.2 continue
• Continue statement can appear only in the body of loop.
• When the continue statement encounters, then the rest of the statements in the loop
are skipped
• The control is transferred to the loop-continuation portion of the nearest enclosing
loop.
• Its syntax is simple just type keyword continue as shown below
continue
• Example:
for I in" welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
• We can say continue statement forces the next iteration of the loop to take place,
skipping the remaining code below continue statement.
13
PPSUnit-II SKNSITS
while(…): for(…):
… …
if condition: if condition:
continue continue
…. …
……. …
❖ DifferentiateBetweenbreak& continue:
Break Continue
Task It terminates the execution of It terminates only the current iteration
Remaining iteration of the loop. Of the loop.
Control after When ‘break’ statement appears When ‘continue’ statement appears the
statement The control goes out of the loop. Control goes at the beginning of the loop.
2.5.3 pass
• It is used when a statement is required syntactically but you do not want any command
or code to execute.
• The pass statement is a null operation.
• No thing happens when it executes.
14
PPSUnit-II SKNSIST
• It is used as placeholder.
• In a program where for some conditions you don’t want to execute any action or what
action to be taken is not yet decided, but we may wish to write some code in future, In
such cases pass can be used.
• Syntax:
Pass
• Example:
for i in “welcome”:
if(i == 'c'):
pass
print (i)
Output:
w
e
l
c
o
m
e
2.6.1 Tuples
Q. What is tuple? Explain how to access, add and remove elements in a tuple
• Tuple is a data structure supported by python.
• A tuple is a sequence of immutable objects. That means you cannot change the
values in a tuple.
• Tuples use parentheses to define its elements.
15
PPSUnit-II SKNSITS
• For example, to access values in tuple, slice operation is used along with the index or
indices to obtain value stored at that index.
• Example:
Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=(5,6,7,8,9,10)
Using square brackets we can get the values from tuples in Python.
t = (10, 5, 20)
Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20
• Tuples are immutable means we cannot add new element into it.
• Also it is not possible to change the value of tuple.
16
Program:
tup1=(“Kunal”,”Ishita”,”Shree”,”Pari”,“Rahul”)
tup1[5]=”Raj”
print(tup1)
Output:
It will raise an error because new element can not be added.
t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])
# tuples contain duplicate elements
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element
t[1] = 100
print(t)
Output :
2
5
(1, 2, 3, 4, 2, 3)
ERROR!
Traceback (most recent call last):
File "<main.py>", line 9, in <module>
TypeError: 'tuple' object does not support item assignment
17
Removing /Deleting elements in Tuple:
Program:
Tup1=(1,2,3,4,5)
delTup1[3]
print(Tup1)
output: It will raise error as ‘tuple’ object doesn’t support item deletion.
del t
print(t)
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
NameError: name 't' is not defined
18
PPSUnit-II SKNSITS
• How ever ,we can delete the entire tuple by using the “del” statement.
Example:
Tup1=(1,2,3,4,5)
delTup1
Operations on Tuple
Q.Explain various operations on Tuple.
• Tuple behave like similar way as string when operators like concatenation
(+),and repetition (*) are used and returns new list rather a string.
• Tuple supports various operations as listed below:
19
PPSUnit-II SKNSITS
2.6.2 Lists
Q.What is list? Explain how elements are accessed, added and removed from list.
• List is a data type in python.
• List is a collection of values(items/ elements).
• The items in the list can be of different data types.
• The elements of the list are separated by comma(,)and written between square
brackets [].
• List is mutable which means the value of its elements can be changed.
• Syntax:
List=[value1,value2, …]
• Example1:
List1=[1,2,3,4]
print(List1)
Output:
[1, 2,3, 4]
• Example2:
List2 =['John','PPS',94]
print(List2)
20
PPSUnit-II SKNSITS
Output:
['John','PPS',94]
21
PPSUnit-II SKNSITS
Output:
Operations on list
Q.Explain various operations on list.
• List behave like similar way as string when operators like concatenation (+), and
repetition (*) are used and returns new list rather a string.
• List supports various operations as listed below:
22
PPSUnit-II SKNSITS
2.6.3 Dictionary
Q.What is dictionary? Explain how to create dictionary, access, add and remove
elements from dictionary.
23
PPSUnit-II SKNSITS
➢ Creating Dictionary
• The syntax to create an empty dictionary can be given as:
Dict = { }
• The syntax to create a dictionary with key value pair
is: Dict = {key1: value1, key2: value2, key3:
value3}
• Example1:
Dict = { }
Print(Dict)
Output:
{}
• Example2:
Dict = {1: "PPS", 2: "PHY"}
print(Dict)
Output:
{1:'PPS',2: 'PHY'}
22
PPSUnit-II SKNSITS
{1:'PPS',3: 'SME'}
{}
Operations on Dictionary:
Method Description
2.6.4 Sets
• Example:
set1 = {1, 2, 3, 4, 5}
print(set1)
set2= set([3, 4, 5, 6, 7])
print(set2)
1) Set Union: The union operation is for combining the elements from both the sets. While combining
the elements it removes the duplicate elements. The | or union( ) is used to perform the union
operation of the set.
Python Program
set1= {1,2,3,4,5}
set2 = {3,4,5,6,7}
result1 = set1 | set2 #using operator |
result2 = set1.union(set2) #using union( ) method
print("result1: ",result1)
print("result2: ",result2)
Output:
result1: {1, 2, 3, 4, 5, 6, 7}
result2: {1, 2, 3, 4, 5, 6, 7}
2) Set Intersection: This operation returns the common element from both the sets. The & operator or the
intersection( ) function is used to find the intersection of two sets.
Python Program
set1= {1, 2, 3,4,5}
set2 = {3,4,5,6,7}
result1 = set1 & set2 #using operator &
result2 = set1.intersection(set2) #using intersection( )
print("result1: ",result1)
print("result2: ",result2)
Output:
result1: {3, 4, 5}
result2: {3, 4, 5}
3) Set Difference: This operation returns the element which is present in one set but not present in another set.
The operator - or function difference( ) is used to find the difference of two sets.
Python Program
set1 = {1,2,3,4,5}
set2 = {3,4,5,6,7}
result1 = set1- set2 #using operator -
result2= set1.difference(set2) #using intersection() method
print("result1: ",result1)
print("result2: ",result2)
Output:
result1: {1, 2}
result2: {1, 2}
4) Symmetric Difference: Symmetric difference: The symmetric difference of two sets is the set of elements
that are in either set, but not in both In Python we can find the symmetric set using the operator ^ or the
method symmetric_difference( ).
Python Program
set1={1,2,3,4,5}
set2= {3,4,5,6,7}
result1 = set1 ^ set2 #using operator ^
result2 = set1.symmetric_difference(set2)
#using symmetric_difference( ) method
print("result1 ",result1)
print("result2 ",result2)
Output:
result1 {1, 2, 6, 7}
result2 {1, 2, 6, 7}