PYTHON Revision PPT Part 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

PYTHON REVISION TOUR II

String
• String are character enclosed in quotes of any type like single
quotation marks, single quotation marks and triple quotation marks.
– ‘Computer’
– “Computer”
– ‘’’Computer’’’
• String are immutable
• Empty string has 0 characters.
• String is sequence of characters, each character having unique
position or index
0 1 2 3 4 5
Forward Indexing
p y t h o n

-6 -5 -4 -3 -2 -1 Backward Indexing
Length of String

Item Assignment is not supported in String


Traversing A String
• Iterating through a element of String , one character at a time.
• Each character are accessible through unique index.

• WAP to print the reverse of a string.


Traversing A String
• Iterating through a element of String , one character at a time.
• Each character are accessible through unique index.

• WAP to print the reverse of a string.


String Operators
• Basic Operators
• Membership Operators
• Comparison Operators
Basic Operators
• + operator is Concatenation Operator
• * operator is Replication Operator
Membership Operators
Operator Working
in Returns true if character /substring occurs in a given string, otherwise false.
not in Returns false if character /substring occurs in a given string, otherwise true.
Comparison Operators
• All relational Operators are comparison operator (<, <=, >, >=, ==,!=).
• In case of characters Uppercase letters are considered smaller than
the lowercase letters.
• Python compares two strings through relational operators using
character by character comparison of their Unicode Values.
Ordinal/ Unicode Value
Characters Ordinal Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
String Slice
• String slice is the part of a String containing some
contiguous character from the string.
• For Example ‘or’ , ‘corpor’, ‘tion’, ‘n’ are slice of
String ‘corporation’.
0 1 2 3 4 5 6 7 8 9 10

c o r p o r a t i o n

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String Function and Methods
• Python offers many built-in functions for string manipulation
Function Functionality Example
string.capitalize( ) Returns a copy of the string with its
first character capitalized in a
sentence.

string.find Returns the lowest index in the string


(sub, start, end) where the substring sub is found
within the slice range of start and
end.
Returns -1 if sub is not present.
Function Functionality Example
string.isalnum( ) Returns true if the
character in the string are
alphanumeric and there is
at least one character.
Otherwise false.

string.isalpha( ) Returns true if all the


characters in the string are
alphabet and there is at
least one character.
Otherwise false.

string.isdigit( ) Returns true if all the


characters in the string are
digits and there is at least
one character.
Otherwise false.
Function Functionality Example
string.islower( ) Returns true if all the cased
characters in the string are
lowercase and there is at
least one character.
Otherwise false.

string.isupper( ) Returns true if all the cased


characters in the string are
uppercase and there is at
least one character.
Otherwise false.
Function Functionality Example
string.lower( ) Returns a copy of the string
converted to lowercase.

string.upper( ) Returns a copy of the string


converted to uppercase.

string.isspace( ) Returns true if there are


only whitespaces characters
in the string and there is at
least one character.
Otherwise false.
Function Functionality Example
string.lstrip([chars] ) Returns a copy of the string
with leading characters
removed.
If used without any argument
, it removes the leading
whitespaces.

string.rstrip([chars] ) Returns a copy of the string


with trailing characters
removed.
If used without any argument
, it removes the leading
whitespaces.
Program
• Program that reads a line and prints its statistics like:
• No of Alphabets:
• No of Upper Case Alphabets:
• No of Lower Case Alphabets:
• No of Digits:
List in Python
• List is a standard data type of Python that can store
a sequence of values belonging to any type.
• List is mutable (modifiable) sequence i.e. element can
be changed in place.
• Example
– List=[1,2,3,4,5]
– List1=['p','r','o','b','l','e','m']
– List2=['pan','ran','oggi','blade','lemon','egg','mango']
Creating List
• List can be created by assigning a variable with the values enclosed in
square bracket separated by comma.
– Example: List=[1,2,3,4,5]
• Creating Empty List: List with no item is a empty list. E.g List=[ ]. It can be
created with the function list1=list().it generates the empty list with the name
list1. This list is equivalent to 0 and has truth value false.
• Creating List from Existing Sequence: List1=list(sequence)
Example: List1=list(‘Computer’)
>>>List1
[’C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’+
• Creating List from keyboard Input: list1=list(input(‘Enter the list item:’)) or
list1=eval(input(‘Enter the list item:’))
List vs String
• Similarities:
– Length
– Indexing Slicing
– Membership operators
– Concatenation and Replication operators
– Accessing Individual elements
• Differences
– Storage : are similar to string , but it stores reference at
each index instead of single characters.
– Mutability: Strings are not mutable, while list are.
Traversing a List
• For <item> in <List>
>>>List1=*’C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’+
>>>for a in List1
print(a)

C
o
m
p
u
t
e
r
List Operations
• Joining Lists: Two Lists can be joined through addition.
>>>l1=[1,2,3]
>>>l2=[4,5,6]
>>>l3=l1+l2
>>>l3
[1,2,3,4,5,6]
• Repeating or Replicating Lists: Multiply(*) operator replicates the List specified number of times
>>>l1=[1,2,3] >>>l1*3 [1,2,3,1,2,3,1,2,3]
• Slicing the List: List slices are the subpart of a list extracted out.List slices can be created through the
use of indexes.
Seq=List[start:stop] : creates list slice out of List1 with element falling in between indexes
start and stop not including stop.
>>>List1=[1,2,3,4,5,6,7,8] >>>seq=List1[2,-3] >>>seq [3,4,5]
List also supports slice steps. Example, Seq=List[start:stop:step] creates list slice out of List with
element falling in between indexes start and stop not including stop, skipping step-1 element
in between.
>>>List1=[1,2,3,4,5,6,7,8] >>>seq=List1[2,7,2] >>>seq [3,5,7]
Using Slices for List Modification
>>> List=*‘add’,’sub’,’mul’+ >>>List*0:2+=*‘div,’mod’+ >>>List
*‘div,’mod’,’mul’+

>>> List=*‘add’,’sub’,’mul’+ >>>List*0:2+=”a” >>>List


*“a”,”mul”+

>>> List=[1,2,3] >>>List*2: +=”604” >>>List


*1,2,3,’6’,’0’,’4’+

>>> List=[1,2,3] >>>List*10:20 +=”abcd” >>>List


*1,2,3,’a’,’b’,’c’,’d’+
List Manipulation
• Appending Elements to a list
append() method adds a single item to the end of the list. List.append(item)
>>> List=[1,2,3] >>>List.append(6) >>>List
[1,2,3,6]
• Updating Element to a list
Assign new value to the element’s index in list. List*index+=<new value>
>>> List=[1,2,3] >>>List[1]=4 >>>List
[1,4,3]
• Deleting Element from a list
Del statement can be used to remove an individual item, or to remove all items identified by a slice.
>>> List=[1,2,3,4,5,6,7,8,9,10] >>>del List[5] >>>List [1,2,3,4,5,7,8,9,10]
>>> List=[1,2,3,4,5,6,7,8,9,10] >>>del List[5:8] >>>List [1,2,3,4,5,10]
>>> List=[1,2,3,4,5,6,7,8,9,10] >>>del List >>>List []
Making True copy of a List
• Assignment does not make a copy of a list.
• Assignment makes two variable to point to same list in memory,
called shallow copying.
List1 2 4 5 6 7

List2
• The changes made in one list will also be reflected to the other list.
• For creating a true copy we need to make
List2=list(List1)
now List1 and List2 are separate list, called Deep Copy
List Functions and Methods
• The index() Method: This function returns the index of first matched item from the list.
List.index(<item>)
>>>list=[12,14,15,17,14,18] >>>list.index(14) 1 If item is not in the list it raises exception value
error.
• The append() Method: This function adds an item to the end of the list.
List.append(<item>)
>>>list=[12,14,15,17] >>>list.append(18) >>>list [12,14,15,17,18]
• The extend() Method: This function adds multiple item to the end of the list.
List.extend(<item>)
>>>list1=[12,14,15,17] >>>list2=[18,19,20] >>>list1.extend(list2)
>>>list1 [12,14,15,17,18,19,20]
• The insert() Method: This function inserts item at the given position in the list.
List.insert(<pos>,<item>)
>>>list1=[12,14,15,17] >>>list1.insert(2,200) >>>list1
[12,14,200,15,17]
• The pop() Method: This removes the item at the given position in the list.
List1.pop() removes last item in the list
List1.pop(3) removes item at index 3 in the list
• The remove() Method: This function removes first occurrence of given item from the list.
List.remove(<item>)
>>>list1=[12,14,15,17] >>>list1.remove(15) >>>list1 [12,14,17]
• The clear() Method: This function removes all the items from the list.
List.clear()
>>>list1=[12,14,15,17] >>>list1.clear() >>>list1 []
• The count() Method: This function returns the count of the item passed as argument.If given item is not in the list it
returns zero.
>>>list1=[12,14,15,14,17]>>>list1.count(14)2
>>>list1=[12,14,15,14,17] >>>list1.count(18) 0
• The reverse() Method: This function reverses the item of the list.This is done “in place”,i.e it does not create
new list.
List.reverse()
>>>list1=[12,14,15,14,17] >>>list1.reverse() [17,14,15,14,12]
• The sort() Method: This function sorts the items of the list, by default in increasing order. This is done “in
place”,i.e it does not create new list.
List.sort()
>>>list1=[12,14,15,14,17] >>>list1.sort() [12,14,14,15,17] It sorts the string in lexicographic manner. If we
want to sort the list in decreasing order, we need to

>>>list1.sort(reverse=True)
Tuples in Python
• Tuple is a standard data type of Python that can store a sequence of
values belonging to any type. Tuples are depicted through parenthesis
i.e. round brackets. Tuples are immutable sequence i.e. element
cannot be changed in place.
• Example
– Tup1=(1,2,3,4,5)
– Tup2=('p','r','o','b','l','e','m‘)
– Tup3=('pan','ran','oggi','blade','lemon','egg','mango‘)
Creating Tuples
• Tuples can be created by assigning a variable with the values enclosed in
round bracket separated by comma.
– Example: tup1=(1,2,3,4,5)
• Tuples can be created in different ways:
– Empty Tuple: Tuple with no item is a empty tuple. It can be created with the function T=tuple( ).
it generates the empty tuple with the name T. This list is equivalent to 0 or ‘ ’.
– Single Element Tuple: Tuple with one item.
T1=(9,) or T1=9, comma is required because Python treats T1=(9) as value not as
tuple element.
– Creating Tuple from Existing Sequence:
T1=tuple(<sequence>)
Example: T1=tuple(‘Computer’)
>>>T1
(’C’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Creating Tuple from Keyboard Input:
Tuples vs List
• Similarities:
– Length
– Indexing Slicing
– Membership operators
– Concatenation and Replication operators
– Accessing Individual elements
• Differences
– Mutability: Tuples are not mutable, while list are.
Tuple Operations
• Joining Tuples: Two tuples can be joined through addition.
>>>t1=(1,2,3)
>>>t2=(4,5,6)
>>>t3=t1+t2
>>>t3
(1,2,3,4,5,6)
• Repeating or Replicating Tuples: Multiply(*) operator replicates the tuple specified number of times
>>>t1=(1,2,3) >>>t1*3 (1,2,3,1,2,3,1,2,3)
• Slicing the Tuples: Tuple slices are the subpart of a tuple extracted out. Tuple slices can be
created through the use of indexes.

Seq=Tuple[start:stop] : creates tuple slice out of t1 with element falling in between indexes start and stop not
including stop.
>>>t1=(1,2,3,4,5,6,7,8) >>>seq=t1[2:-3] >>>seq (3,4,5)
tuples also supports slice steps. Example, Seq=Tuple[start:stop:step] creates tuple slice out of tuple with
element falling in between indexes start and stop not including stop, skipping step-1 element in between.
>>>t1=(1,2,3,4,5,6,7,8) >>>seq=t1[2:7:2] >>>seq (3,5,7)
Unpacking Tuples
Forming a tuple from individual values is called packing
and creating individual values from a tuple’s elements
is called unpacking.
Deleting Tuples
• We cannot delete individual item of a tuple.
• del statement deletes the complete tuple.
Tuple Functions and Methods
• The len( ) Method: This function returns the length of the tuple, i.e. the count of elements in the
tuple. len(<tuple>)

• The max( ) Method: This function returns the element from the tuple having maximum value
. max(<tuple>)
• The min( ) Method: This function returns the element from the tuple having minimum value
. min(<tuple>)

• The index( ) Method: This function returns the index of first matched item from the
tuple. Tuple.index(<item>)

If item is not in the list it raises exception value


• The count( ) Method: This function returns the count of the item passed
as argument. If given item is not in the tuple it returns zero.
tuple.count(<item>)
• The tuple( ) Method: This function creates tuples from different types of values.
tuple(<sequence>)

tuple( ) can receive argument of sequence


type only, like string or list or dictionary. Any
other type of value will lead to an error.
Dictionary - Key :Value Pairs
• Are collection or bunch of values in a single variable.
• These are collection of key-value pairs.
• It associates key to values.

Dictionaries are mutable, unordered collections with


elements in the form of a key:value pair that associate
keys to value.
Creating a Dictionary
• Dictionary can be created by including the key : value pair in curly braces.
– Syntax: <dictionary name>=,<key>:<value>,< key>:<value>, ……….-
– Example: dictionary by the name teachers that stores name of teachers as
key and subjects being taught by them as value of respective key
teachers={"Lovely":"Computer Science","Suman":
"Geography", "Rupam":"Maths","Babli":"Pol Science"}
Keys of dictionary must be of immutable type.
key : value pair key value
“Lovely”:”Computer Science” Lovely Computer Science
”Suman”: “Geography” Suman Geography
”Rupam”:”Maths” Rupam Maths”
”Babli”:”Pol Science” Babli Pol Science
Accessing elements of a Dictionary
• Dictionary is accessed through its key.
 Syntax: <dictionary name>[<key>]

 Mentioning dictionary name without any square bracket displays the entire content of
the dictionary.
Characteristics of a Dictionary
• Unordered Set: order that the keys are added doesn't
necessarily reflect what order they may be reported back.
• Not a Sequence
• Indexed by Keys, Not Numbers
• Keys must be Unique: More than one entry per key not allowed.
Which means no duplicate key is allowed. When duplicate keys
encountered during assignment, the last assignment wins.
• Mutable: which means they can be changed
• Internally Stored as Mapping: is a mapping of
unique keys to values
Traversing a Dictionary
• Traversing means accessing each element of a collection.
• For loop helps to traverse each elements of dictionary as per following
syntax: for <item> in <dictionary>:
process each item here

• Dictionaries are un-ordered set of elements, the printed order of elements is not same
as the order you stored the elements in.
Exercise: WAP to create phone dictionary of all your friends and print it.
Accessing Keys or Values Simultaneously

• To see all keys in dictionary we write <dictionary>.keys( )

• To see all values in dictionary we write <dictionary>.values( )

• We can convert the sequence returned by keys( ) and values(


) function by using list( )
Adding Element to Dictionary
Updating Existing Element in a Dictionary
• Change the value of an existing key using assignment.
<dictionary name>[<key>]=<value>

• Make sure key must


exist in the dictionary
otherwise new entry
will be added to the
dictionary.
Deleting Element From a Dictionary

• There are two methods for deleting element from


a dictionary
– To delete a dictionary element or a dictionary entry, i.e key:value
pair we will use del command.
• Syntax:
del <dictionary>[key]
– pop( ) method
• Syntax:
<dictionary>.pop(<key>)
This method will not only delete the key:value pair for mentioned key but also
return the corresponding value.

If we try to delete a key which does not exist, python gives KeyError.
pop( ) method allows you to specify what to display when the
given key does not exist, rather than the default error
message, with the following syntax:
<dictionary>.pop(<key>,<in case of error show me>)
Checking of Existence of a Key
• Membership operators in and not in checks the presence of key in a dictionary. It does
not check the presence of value.
– Syntax:
<key> in <dictionary>
returns true if given key is present in the dictionary, otherwise false.
<key> not in <dictionary>
returns true if given key is not present in the dictionary, otherwise false.
Checking of Existence of a Value
Dictionary Functions and Methods
• The len() Method: This function returns the length of the
dictionary. len(<dictionary>)

• The clear() Method: This function removes all the items from the
dictionary. <dictionary>.clear( )

• Differentiate between clear( ) and del.


• The get( ) Method: This function returns the corresponding value for the key.
<dictionary>.get(key,[default])

• The item( ) Method: This function returns all of the item in the dictionary as a sequence
of key:value pair.
<dictionary>.items( )
• The key( ) Method: This function returns all of the keys in the
dictionary. <dictionary>.keys( )

• The values( ) Method: This function returns all the values from the dictionary as a
sequence. <dictionary>.values( )
• The update( ) Method: This function merges key: value pairs from the new dictionary into
the original dictionary , adding or replacing as needed.
• <dictionary>.update(<new dictionary>)
Sorting Techniques: Bubble Sort
• Bubble Sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they are
in wrong order.
Coding:
void bubble_sort( int A[ ], int n ) {
int temp;
for(int k = 0; k< n-1; k++) {
# (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations

for(int i = 0; i < n-k-1; i++) {


if(A[ i ] > A[ i+1] ) {
// here swapping of positions is being
done. temp = A[ i ];
A[ i ] = A[ i+1 ];
A[ i + 1] = temp;
} }}}
Sorting Techniques: Insertion Sort
• Insertion sort is a simple sorting algorithm that works the
way we sort playing cards in our hands.
Coding:
void insertion_sort ( int A[ ] , int n)
{ for( int i = 0 ;i < n ; i++ ) {
/*storing current element whose left side is checked for its correct position .*/
int temp = A[ i ];
int j = i;
/* check whether the adjacent element in left side is greater or less than
the current element. */
while( j > 0 && temp < A[ j -1]) {
// moving the left side element to one position forward.
A[ j ] = A[ j-1];
j= j - 1;
}
// moving current element to its correct position.
A[ j ] = temp;
}}

You might also like