AR20 Python Unit-II
AR20 Python Unit-II
Python Programming
Unit-II
if statement syntax:
if test expression:
statement(s)
In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first un indented line marks the end.
Example:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
Python Programming Raghu Engineering College 3
if else
Syntax of if...else:
if test expression:
Body of if
else:
Body of else
body of if only when test condition is True. If the condition is False, body of else is
executed. Indentation is used to separate the blocks.
Example:
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
• The if block can have only one else block. But it can have
multiple elif blocks.
Example:
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Loops are often used when we have a piece of code that we need to repeat for
(i) N number of times or (ii) until a condition becomes true or false
Concepts in loops:
• For loop
• While loop
• Nested loops
• Break
• Continue
Range function iterates i value starting from 1st argument up to but not including 2nd
argument. So i value is iterated only up to 4, but not 5
Python Programming Raghu Engineering College 9
for loop
The third argument in range function indicates the difference between each
number in the sequence:
Example:
for i in range(1,10,2):
print(i)
Output:
1
3
5
7
9
Output:
0
-2
-4
-6
-8
Python Programming Raghu Engineering College 11
while loop
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while test_expression:
body
Example:
n = 10
i=1
while i <=n:
if(i%2!=0):
print(i,end=" ")
i=i+1
Output:
13579
Output:
1
22
333
4444
55555
Python Programming Raghu Engineering College 14
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.
Example:
for val in "string":
if val == "i":
break
print(val)
Output:
s
t
r
• If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Example:
for val in "string":
if val == "i":
continue
print(val)
Output:
s
t
r
n
g
• The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.
• Sometimes there may be situations so that we do not want to execute any statement when
a particular condition is true or false.
x=5
y=10
if(x==y):
else:
print("not equal")
Here we do not want to execute any statement when the if condition becomes true,
but when this code is executed, we get an error saying “expected and indented block”.
x=5
y=10
if(x==y):
pass
else:
print("not equal")
pass keyword can be used in all the control flow statements like if, elif, else, for ,while.
• List
• Tuple
• Set
• Dictionary
• Comprehension
• The key feature of a list is that it can have elements that belong to different data types.
Program: Program:
l=[10,16,1000,98] l=[10,16.53,"hello"]
print(l) print(l)
•The index of -1 refers to the last item, -2 to the second last item
and so on.
list1 = ['tiger','lion','dog','cat','horse']
• To access values in lists, square brackets are used to slice along with
the index or indices to get value stored at that index.
Program: Program:
x=[5,10,15,20,25] x=[5,10,15,20,25]
for i in x: for i in range(0,len(x)):
print(i,end=" ") print(x[i],end=" ")
Program:
cities=["vizag","hyderabad","delhi","mumbai"]
for city in cities:
print(city,end=" ")
Sample Output:
vizag hyderabad delhi mumbai
• split() function assumes the default argument as space. Instead of space, any
other symbol can also be used as a separator between values as shown
below:
l = list(input().split(“,”))
Here user needs to enter list of values separated by comma.
Program: Program:
l = list(input().split()) l = list(input().split(","))
print(l) print(l)
• You can also append new values in the list and remove existing value(s)
from the list using the append() method and del statement respectively.
Program: Program:
s="hello" list1=[1,2,3,4]
print(s) print(sum(list1))
l=list(s)
print(l) Sample Output:
Sample Output: 10
hello
['h', 'e', 'l', 'l', 'o']
Program: Program:
l=[[1,2,3],[4,5,6]] l=[[1,2,3],['abc','xyz'],[4,5,6]]
print(l[0][2]) print(l[1][1])
print(l[1][0]) print(l[1][1][2])
print(l[1][1]) print(l[2])
Sample Output: Sample Output:
3 xyz
4 z
5 [4, 5, 6]
Python Programming Raghu Engineering College
Nested Lists: Traversing
Program:
a=[[1,2,3,4],[5,6],[7,8,9]]
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=" ")
print()
Sample Output:
1234
56
789
Program:
a=[[1,2,3,4],[5,6],[7,8,9]]
for row in a:
for ele in row:
print(ele,end=" ")
print()
Sample Output:
1234
56
789
Program:
r=int(input()) # r represents number of rows(or number of lines)
list2d=[] # list2d represents variable name of a 2d list
for i in range(r): # repeating for r times
list1d=list(map(int,input().split())) # reading each line into 1d list
list2d.append(list1d) # appending 1d list into a 2d list
print(list2d)
Sample input2:
Sample input1: 4
3 12
1234 3456
9
5678
3614721
2341
Sample output2:
Sample output1: [[1, 2], [3, 4, 5, 6], [9], [3, 6, 1, 4, 7,
[[1, 2, 3, 4], [5, 6, 7, 8], [2, 3, 4, 1]] 2, 1]]
Python Programming Raghu Engineering College
Cloning Lists
• If we try to copy one list into the other by using assignment operator, now both the lists will
be allocated same addresses.
• This means that both the lists will be treated as same objects.
• So if a change is made in one list, it will be reflected to the other list also.
list1=[10,20,30,40,50]
list2=list1 #copying using assignment operator
• If we want to modify a list and also keep a copy of the original list, then we
should create a separate copy of the list (not just the reference).
• This process is called cloning. In this cloning process the new list called as
Shallow copy
• The slice operation or copy() function is used to clone a list.
Program: Program:
list1=[10,20,30,40,50] list1=[10,20,30,40,50]
list2=list1 list2=list1[:] #copying using slice
list2[1]=25 #both lists are modified list2[1]=25 #only list2 is modified
print(list1) print(list1)
print(list2) print(list2)
Sample Output: Sample Output:
[10, 25, 30, 40, 50] [10, 20, 30, 40, 50]
[10, 25, 30, 40, 50] [10, 25, 30, 40, 50]
Python Programming Raghu Engineering College
List Comprehensions
• Python also supports computed lists called list comprehensions having
the following syntax.
Program: Program:
squares=[] squares=[i**2 for in range(11)]
for i in range(11): print(squares)
squares.append(i**2)
print(squares) Sample Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
Sample Output: 100]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
100]
Program: Program:
odds=[] l=range(1,11)
for i in range(1,11): odd=[x for x in l if x%2==1]
if i%2!=0: print(odd)
odds.append(i)
print(odds) Sample Output:
Sample Output: [1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
• A list also has sort() method which performs the same way as sorted().
• Only difference being, sort() method doesn't return any value and
changes the original list itself where as sorted() method only returns
sorted list but it does not change the original list.
Program: Program:
l=[50,20,40,10,30] l=[50,20,40,10,30]
print(sorted(l)) l.sort()
print(l) #original list not sorted print(l) #original list sorted
Program: Program:
l=['mech','eee','ece','civil','cse'] l=['mech','eee','ece','civil','cse']
l.sort()#strings sorted alphabetically print(sorted(l))
print(l) print(l)
Program: Program:
l=['mech','eee','ece','civil','cse'] l=[50,20,10,40,30]
l.sort(reverse=True) #descending print(sorted(l,reverse=True))
print(l) print(l)
• This means that while you can change the value of one or more items in
a list, you cannot change the values in a tuple.
• Second, tuples use parentheses to define its elements whereas lists use
square brackets.
• For creating a tuple, generally we need to just put the different comma-
separated values within a parentheses as shown below:
t = (val1, val2,….. )
Example: t=(10,20,30,40,50)
• For example, to access values in tuple, slice operation is used along with
the index or indices to obtain value stored at that index
Program:
t=(10,20,30,40,50,60,70,80) Sample Output:
print(t[2:4]) (30, 40)
print(t[1:]) (20, 30, 40, 50, 60, 70, 80)
print(t[:5]) (10, 20, 30, 40, 50)
print(t[-2]) 70
Program:
t1=(10,20,30,40,50)
t2=("abc","xyz")
t3=t1+t2
print(t3)
Sample Output:
(10, 20, 30, 40, 50, 'abc', 'xyz')
t1=(10,20,30,40,50)
del t1[2] or t1.remove(30) will not work
• The tuple thus, formed has one element from each sequence.
• The * operator can be used in conjunction with zip() to unzip the list.
zip(*zippedList)
Python Programming Raghu Engineering College
The zip() function
• A set is created by placing all the elements inside curly brackets {},
separated by comma or by using the built-in function set().
• Example:
• st = {1,2,3,4,5}
• When we print st, {1,2,3,4,5} may not be printed in order, but all the
values will be printed definitely without any duplicates.
Program: Program:
st={1,2,'cse','ece',2,3,'cse'} t=(1,2,'cse','ece',2,3,'cse')
print(st) st=set(t) #converts tuple to set
print(t)
Sample output: print(st)
{1, 2, 3, 'cse', 'ece'} Sample output:
(1, 2, 'cse', 'ece', 2, 3, 'cse')
{1, 2, 3, 'ece', 'cse'}
remove(): Program:
syntax: s1={1,2,3,4,5}
s.remove(x) s1.remove(3)
print(s1)
removes element x from set s.
Returns keyerror if x is not Sample output:
present. {1, 2, 4, 5}
discard(): Program:
s1={1,2,4,5}
syntax: s1.discard(3)
s.discard(x) print(s1)
pop(): Program:
s1={1,2,3,4,5}
syntax: print(s1.pop())
s.pop() print(s1)
len(): Program:
s={1,2,3,4,5}
syntax: print(len(s))
len(s)
Sample output:
Returns the length of a set s. 5
in: Program:
s={1,2,3,4,5}
syntax: print(7 in s)
x in s
Sample output:
Returns True if x is present in s, False
False otherwise
issubset(): Program:
s={1,2,3,4,5}
syntax: t={1,2,3}
s.issubset(t) print(s.issubset(t))
or
s<=t Sample output:
False
Returns True if s is subset of t,
False otherwise
Python Programming Raghu Engineering College 91
Set functions: issuperset()
issuperset(): Program:
s={1,2,3,4}
syntax: t={1,2,3}
s.issuperset(t) print(s>=t)
or
s>=t Sample output:
True
Returns True if s is superset of t,
False otherwise
Python Programming Raghu Engineering College 92
Set functions: union()
union(): Program:
syntax: s={1,2,3,4,'abc','def'}
s. union(t) t={1,2,3,6,'abc',9}
or print(s.union(t))
s|t
Sample output:
Returns a new set that has {1, 2, 3, 'abc', 4, 'def', 6, 9}
elements from both sets s and t
intersection(): Program:
syntax: s={1,2,3,4,'abc','def'}
s.intersection(t) t={1,2,3,6,'abc',9}
or print(s&t)
s&t
Sample output:
Returns a new set that has {1, 2, 3, 'abc'}
elements which are common to
both sets s and t.
Python Programming Raghu Engineering College 94
Set functions: intersection_update()
intersection_update(): Program:
s={1,2,3,4,'abc','def'}
syntax: t={1,2,3,6,'abc',9}
s. intersection_update(t) s.intersection_update(t)
print(s)
Returns a set s that has elements
which are common to both sets s Sample output:
and t. {1, 2, 3, 'abc'}
s is updated with new values.
Python Programming Raghu Engineering College 95
Set functions: difference()
difference(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. difference(t) z=s-t
or print(z)
s-t
Sample output:
Returns a new set that has {1, 3, 4, 6}
elements in s but not in t.
Python Programming Raghu Engineering College 96
Set functions: difference_update()
difference_update(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. difference_update(t) s.difference_update(t)
print(s)
Returns a set s that has elements
in s but not in t. And update s Sample output:
with new values. {1, 3, 4, 6}
symmetric_difference(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. symmetric_difference(t) z=s.symmetric_difference(t)
or print(z)
s^t
Sample output:
Returns a new set with elements {1, 3, 4, 6, 10, 15}
in either s or t but not both.
Python Programming Raghu Engineering College 98
Set functions: symmetric_difference_update()
symmetric_difference_udpate(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. s.symmetric_difference_update(
symmetric_difference_update(t) t)
print(s)
Returns a set s with elements in Sample output:
either s or t but not both. {1, 3, 4, 6, 10, 15}
enumerate(): Program:
s={'a','b','c','d'}
syntax: for i in enumerate(s):
enumerate(s) print(i,end=" ")
• Each key is separated from its value by a colon (:), and consecutive items
are separated by commas.
Sample output:
101
ram
75.4
Returns the length of dictionary, that is the number of key value pairs.
dictionary.get(key):
Returns the value for the key passed as argument. If key is not present, returns None
• First step in reading a dictionary is to read all the elements into a list.
• Now to create a dictionary from this list:
– starting from first element every alternative element should be a key.
– starting from second element every alternative element should be a value.
• This can be done by using the loop:
for i in range(0,len(list),2):
dict[key] = value
From this list to create a dictionary, we need to assign key value pairs as
shown below:
dict[‘rollno’] = 101 or dict[list[0]] = list[1]
dict[‘name’] = ‘ram’ or dict[list[2]] = list[3]
dict[‘marks’] = 76 or dict[list[4]] = list[5]
which is nothing but dict[list[i]] = list[i+1], where i is every alternative
index from starting to ending of list.
Output:
rollno,101,name,ram,marks,76
{'rollno': '101', 'name': 'ram', 'marks': '76'}
• Second, in lists, you can use indexing to access a particular item. But,
these indexes should be a number. In dictionaries, you can use any type
(immutable) of value as an index. For example, when we write
Dict['Name'], Name acts as an index but it is not a number but a string.
• Fourth, the key-value pair may not be displayed in the order in which it
was specified while defining the dictionary. This is because Python uses
complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary. This also makes dictionary preferable to use over
a list of tuples.
Python Programming Raghu Engineering College Slide 128
When to use which Data Structure
• Use lists to store a collection of data that does not need random access.
• Use a set if you want to ensure that every element in the data structure
must be unique.
• Use tuples when you want that your data should not be altered.