0% found this document useful (0 votes)
22 views36 pages

XI Computer Science Gist-04

messi

Uploaded by

Aryadeep Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views36 pages

XI Computer Science Gist-04

messi

Uploaded by

Aryadeep Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Class XI

Computer Science
Gist-4 of Lessons covered between 4/11/2023 to 16/02/2024
Working with In-Built String Manipulation Methods
▪ string.capitalize(): Returns a copy of the string with its first character capitalized and all other characters
changed to lowercase

▪ string.title(): Returns a copy of the string with the first alphabet of each word in uppercase

▪ string.isspace(): Returns True if all characters in the string are white space characters (like newline \n, tab
\t or space). Else returns False. Returns False for a null string.

▪ string.isalnum(): Returns True if all characters in the string are alphanumeric i.e. either alphabets or digits
or both. Else returns False.

▪ string.isalpha(): Returns True if all characters in the string are alphabets only. Else returns False

▪ string.isdigit(): Returns True if all characters in the string are digits only. Else returns False

▪ string.islower(): Returns True if all characters in the string are in lowercase. Else returns False. At least one
character should be an alphabet for it to return True.
▪ string.isupper(): Returns True if all characters in the string are in
uppercase. Else returns False. At least one character should be an
alphabet for it to return True.

▪ string.lower(): Returns a copy of the string with all alphabets


converted to lowercase

▪ string.upper(): Returns a copy of the string with all alphabets


converted to uppercase

▪ string.find( sub, start, end ): Returns the lowest index in the string, where the sub-string sub is found
within the slice range between start and end. If start and end are not given, then uses the entire string.
Returns -1 if sub is not found.

▪ string.count(): Counts the number of occurrences of a sub-string in a string.

▪ string.join(): Joins a string or a character in-between each member of a sequence.


▪ string.split(): Splits a string by white-space characters (space, newline, tab) when no splitting string is
specified (by default). Else it splits at the specified string. The result is a LIST containing the split string
parts. The splitting string is removed and is not present in the resultant list.

▪ string.partition(): Partitions a string with respect to a given sub-string, into 3 parts always, to form a tuple.
In case the sub-string occurs more than once, ONLY the first occurrence is used. The three parts are the
part on the left of the partition, the partition string and the part on the right of the partition string.

▪ string.replace(): Replaces all occurrences of a given string (first string) with another string (second string).

Replaces By ‘i’
‘ro’

▪ index( ): Returns the index of the first occurrence index of a substring in a string. If substring is not
present, it raises an error. It can be used with a string, list, tuple.

▪ startswith( sub, start, end ): Returns True if a string starts with a given character or sub-string within a
range. Else returns False.
▪ endswith( ): Returns True if a string ends with a given character or sub-string within a range. Else returns
False.

▪ lstrip( ): Removes all occurrences of a character or sub-string


from the left of a string only. In case no argument is
provided, all whitespace characters i.e. ‘ ‘, ‘\n’, ‘\t’ are
removed from the left of the string.
For s.lstrip(‘create’), Python will one by one take a character
from the left of the string ‘terracotta’ and see if that character
is present in the string ‘create’ or not. If present, it will be removed from ‘terracotta’. The process stops
when a particular character from ‘terracotta’ is not present in ‘create’. Hence, ‘t’, ‘e’, ‘r’, ‘r’, ‘a’, ‘c’ are
removed from the left of ‘terracotta’ as these characters are present in the string ‘create’. The process
stops as the next character ‘o’ is not present in ‘create’
▪ rstrip( ): Removes all occurrences of a character / sub-string
from the right of a string only. In case no argument is
provided, all whitespace characters i.e. ‘ ‘, ‘\n’, ‘\t’ are
removed from the right of the string.
For s.rstrip(‘create’), Python will one by one take a character
from the right of the string ‘terracotta’ and see if that
character is present in the string ‘create’ or not. If present, it will be removed from ‘terracotta’. The process
stops when a particular character from ‘terracotta’ is not present in ‘create’. Hence, ‘a’, ‘t’, ‘t’, are removed
from the right of ‘terracotta’ as these characters are present in the string ‘create’. The process stops as the
next character ‘o’ is not present in ‘create’.
▪ strip( ): Removes all occurrences of a character or sub-string
from both ends of a string. In case no argument is provided, all
whitespace characters i.e. ‘ ‘, ‘\n’, ‘\t’ are removed from the
right of the string
For s.strip(‘create’), Python will first take each character from
the left of the string ‘terracotta’ and see if that character is
present in the string ‘create’ or not. If present, it will be removed from ‘terracotta’. The process stops when
a particular character from ‘terracotta’ is not present in ‘create’. Hence, ‘t’, ‘e’, ‘r’, ‘r’, ‘a’, ‘c’ are removed
from the left of ‘terracotta’ first, as these characters are present in the string ‘create’. The left side process
stops as the next character ‘o’ is not present in ‘create’.
Next, Python will one by one take a character from the right of the string ‘terracotta’ and see if that
character is present in the string ‘create’ or not. If present, it will be removed from ‘terracotta’. The process
stops when a particular character from ‘terracotta’ is not present in ‘create’. Hence, ‘a’, ‘t’, ‘t’, are removed
from the right of ‘terracotta’ as these characters are present in the string ‘create’. The process stops as the
next character ‘o’ is not present in ‘create’.
The final character left after the characters are removed from both the ends of ‘terracotta’ is ‘o’.

Problems:
1. Program to input a sentence and find how many number of words are present in the sentence,
2. Write a program to input a sentence and find how many times the letter ‘a’ or ‘A’ occurs in the string.

3. Input a sentence and count:


a) Number of alphabets
b) Number of digits
c) Number of spaces
d) Number of uppercase letters
e) Number of lowercase letters
f) Any other remaining characters

4. Input a sentence and count the number of vowels in the sentence.

5. Program to input a word and check if it is a palindrome or not


6. Write a program to find how many times the word ‘HE’ occurs in a sentence. Word can be present as “HE,
‘He’, ‘he’, or ‘hE’.

7. Input a sentence and print all the words that start with ‘T’ or ‘t’ and also print a total count of all those words.

8. Write a program to input a sentence and capitalize the last letter of every word in a sentence.

9. Write a program to input a sentence and find how many words end with ‘e’ or ‘E’. Also print those words.

10. Write a program to input a sentence and print all the locations of the sub-string ‘th’ in the sentence.
p p p p

11. Find the output of the following code

12. Find the output of the following code

LISTS
What is a List?
• A List is a comma separated mutable sequence of ordered values of any data type
• The term mutable means the values in a list can be modified or changed in place without the requirement to
create a new list
• The term ordered values means the order in which you enter the values in a list is the same as the order in
which it is stored in memory or displayed
• The values in a list are separated by commas and put within a pair of square brackets [ ]
• Example of simple lists: L1 = [ 8.5, 2.5, 6.2 ], L2 = [ 1, 0, 1, 1 ], L3 = [ ‘cat’, ‘mat’, ‘bat’ ], L4 = [ 7, 9.3, ‘pi’ ]
• When an element of a list is itself a list, then it is called a nested list
• Example of nested list: L5 = [ 2, 4, [ 7.1, 3.5, 9.2 ], 8 ]
A list can be created in any one of the following ways:
• L=[] print(L) → [ ] #Creates empty or null list
• L=[4] print(L) → [ 4 ] #Creates a single value list
• L = [ 3, 6, 8 ] print(L) → [3, 6, 8] #Creates a list with 3 elements
• L = list ( ) print(L) → [ ] #Creates empty list using list function
• L = list ( [ 3, 5, 8 ] ) print(L) → [3, 5, 8] #Creates a new list from another list
• L = list ( 'python' ) print(L) → ['p', 'y', 't', 'h', 'o', 'n’] #List from string sequence
• L = list ( ( 3, 7, 4 ) ) print(L) → [3, 7, 4] #Creates list from tuple sequence
• L = list ( 12345 ) print(L) → ERROR #Can’t create list from a non-sequence
• L = list ( [ 12345 ] ) print(L) → [12345] #Creates a single value list
• L = list ( { 2:3, 5:6, 3:8 } ) print(L) → [2, 5, 3] #Creates list from dictionary keys
A list can be created in any one of the following ways:
• The value input will be first input as a string by the input() function.
• This string will then be converted to a list using eval() function
• The eval() function will read the string and convert it to a proper list keeping the data types same and as
input by the user
• Hence any type of data can be input using the eval() function, which then converts it to a proper data-
type
Different ways of inputting a list from the user:
• Using eval() function

Remember: If the [ ] brackets are not given during input, a tuple will be formed:

• Using append method:


The append() method is used to take input from the user and add it to the end of the list.
To use the append() method you first ask
the user the number of values n to store.
The for loop then runs n number of times.
Each time a value is input from the

• Using a loop

• First an empty list is to be created { L=list() can also be used for this }
• Next, a for loop can be used to input the values to be stored, from the user
• The value val is then added to the list as a single element
• Note that for a list, the new value is added to the list as a single element LIST as [val]
List index System
• Being a sequence like a string, lists also follow an index system to access an element from the list
• The first element is given an index of 0 and the last element, an index of length-1
• Like a string these also use a negative index system with the last element having negative index -1 and first
element -(length)
• Example: L = [ 6.2, 9.1, 5, 8.2, ‘ab’, 7 ]
Length = total elements = 6
First element +ve index = 0
First element -ve index = -(len) = -6
Last element +ve index = (6-1) = 5
Last element -ve index = -1
Accessing an Element from a List
Once you create a list, the individual elements of a list can
be accessed using a pair of square brackets. The following
examples will make this clear:

The use of List Slicing:


Like a string (a sequence), you can form a slice from elements of a list. The
same rules apply for a slice:
• Slice: A slice is formed by taking a part of the list from the original
• Range: The slice starts from a starting index and takes all elements up to
1 less than the ending index. The index used to get the slice
range can use both +ve / -ve values
• Step: A third optional step parameter can be provided to skip
elements while choosing the elements of a slice.
o A positive step value skips elements from left to right
o A negative step value skips elements from right to left
Examples of slices are shown on the right with the help of the list L.
The slices are similar to the slices in a string.

Some properties of lists:


You can add two lists to create a new list using the + operator

You can repeat a list/tuple multiple times using the * operator. Multiplying by 0 gives a null list

Using slices for Modifying List Content


Concept of Shallow Copy and True Copy: Creating shallow copies and true copies of lists

When shallow copy is made,


only a new name is assigned
to the same list. No new list
is formed. Both names point
to same list and changes
made using either name
affects the same list.
A true copy is formed when
using list() function. Here,
change made in one list does
not affect the other list.

In-Built List Manipulation Functions & Methods


1. len( ): Returns the length of a list, i.e. the number of elements in the list

2. append( ): Used to add an element at the end of an existing list. No new list is created

3. extend( ): Used to add the content of a list at the end of another list L. The values are added as the elements of
the list L and NOT as a sub-list. No new list created.

This is unlike the append() method, which will add the second list as a sub-list as shown below:

4. index( ): Returns the index of the first matched item (given by user) from the list
In case index given is out of range, Python
shows an error
5. reverse( ): Used to reverse the content of a list

6. insert( ): Used to insert a value at a given index in the list. It has two arguments. The first argument is the index
at which to insert, and the second argument is the value to be inserted. Different possibilities are:

7. remove( ): Used to remove the first occurrence (from left) of a value in the list. The value to remove is to be
given. THE REMOVED VALUE IS NOT RETURNED. If value is not present in the list, then error message given:

8. sort( ): Used to arrange a list in ascending/descending order.

9. pop( ): Used to remove a value from the list. THE POPPED VALUE IS RETURNED (unlike the remove() method).
Index of value to be popped is to be given. If no index given, then by default removes the LAST VALUE from
the list. If index is out of range, then error message given.
10. count( ): Counts number of occurrences of a value in a list and returns the count:

11. sum( ): The function finds the sum of values in the list and returns the sum. List must have all numeric values.

12. max( ): The function finds the maximum value in a list and returns the maximum. List must have all values of
the same data type

13. min( ): The function finds the minimum values in a list and returns the minimum. List must have all values of
the same data type

14. The del statement: The del statement can be used to delete:
• A single element from the list
• A slice of elements from the list
• The entire list

Some Common Errors in writing Code for List


Apart from the len(), index(), pop(), and count(), no other method returns a value. If you store the returned value
from the other methods, it will store the special value None. Some examples showing this, are given below:
>>> L = [2, 5, 8, 3, 7]
>>> L = L . append(2) #WRONG USE. Should be ONLY L . append(2)
>>> print(L)
None
>>> L = [2, 5, 8, 3, 7]
>>> x = L . remove(8) #WRONG USE. Should be ONLY L . remove(8)
>>> print(x)
None
>>> L = [2, 5, 8, 3, 7]
>>> L = L . sort() #WRONG USE. Should be ONLY L . sort()
>>> print(L)
None
Comparing Lists
• Two lists are considered identical if these have the same values in the same order
• For inequality, a list with the first larger value from the left is considered larger in value
• The pair of values that decide the result during comparison, should be of the same data type
o >>> print ( [2, 4, 6] == [2, 4, 6] ) → True #As both lists are identical
o >>> print ( [2, 4, 6] > [2, 4, 8] ) → False #First two values same, third value 6 < 8
o >>> print ( [4, 3, 6] > [7, 8, 9] ) → False #As first values 4 < 7
o >>> print ( [1, 4, 6, 3] < [2] ) → True #As first value 1<2, remaining not checked
o >>> print ( ['bat', 'mat'] < ['bat', 'pat', 'rat'] ) → True #As 'mat' < 'pat' in dictionary
Nested Lists / Tuples
• When a list is placed inside another list, it is called a nested list
• There can be multiple nesting of lists/tuples
• In case of a NESTED LIST/TUPLE, multiple [ ] brackets can be used to access the list/tuple elements as shown
below:

Problems on List
1. To input a list and find the average of values in the list.
Normally the append function is used to create a list in the manner shown

2. To input a list and find the frequency of a given element in the list without using the count function.
3. To search a given value from the list without using count function

4. To input a list and find the maximum value from the list without using max function

5. Input a list. Next add the value 10 to every element of the list.

6. Input a list. Next multiply each even element in the list by 3.

7. Input a list. Next multiply each element at an even index in the list, by 2.
8. Program to create two lists from a given list. The first list will contain values which occur multiple times and
the second list will contain values that occur only once in the main list.

9. Find the outputs:

10. Find the outputs:


TUPLE type data
Some General Properties of Tuple:
• A Tuple is a comma separated immutable sequence of ordered values of any data type
• Immutable means the values in a tuple cannot be modified or changed in place and changing any element
creates a new tuple
• The term ordered values means the order in which you enter the values in a tuple is the same as the order in
which it is stored in memory or displayed
• The values in a tuple are separated by commas and put within a pair of first brackets ( )
Example of simple tuples:
T1 = ( 8.5, 2.5, 6.2 ), T2 = ( 1, 0, 1, 1 ), T3 = ( ‘cat’, ‘mat’, ‘bat’ ), T4 = ( 7, 9.3, ‘pi’ )
• When an element of a tuple is itself a tuple, then it is called a nested tuple
Example of nested tuple:
T5 = ( 2, 4, ( 7, 3, 9 ), 8 )
Different ways of creating a tuple
A tuple can be created in any one of the following ways:
• T=() print(T) → ( ) #Creates empty or null tuple
• T = ( 3, 6, 8 ) print(T) → (3, 6, 8) #Creates a tuple with 3 elements
• T = tuple( ) print(T) → ( ) #Creates empty tuple using tuple function
• T = tuple( [ 3, 5, 8 ] ) print(T) → (3, 5, 8) #Creates a tuple from a list sequence
• T = tuple( 'code' ) print(T) → (‘c', ‘o', ‘d', ‘e') #Tuple from string sequence
• T = tuple( (5, 9, 2) ) print(T) → (5, 9, 2) #Creates new tuple from tuple sequence
• T = ( 3, ) print(T) → ( 3, ) #Creates a SINGLE value tuple
• T=(3) print(T) → 3 #DOES NOT create a tuple
• T = tuple( (65,) ) print(T) → ( 65, ) #Creates a SINGLE value tuple
• T = tuple( (57) ) ERROR #As (57) is not a sequence or a tuple
• T = tuple({ 2:3, 5:6}) print(T) → ( 2, 5 ) #Creates tuple from the dictionary keys

Inputting a Tuple using eval( )

• The value input will be first input as a string by the input() function.
• This string will then be converted to a tuple using eval() function
• Unlike the tuple() functions the eval() function will read the string and convert it to a proper tuple keeping
the data types same and as input by the user
Inputting a Tuple using a Loop
REMEMBER: You CANNOT use the
append( ) method to input elements of a
tuple.

• First an empty tuple is to be created [ T=tuple() can also be used for this ]
• Next, a for loop can be used to input the values to be stored, from the user
• The value val is then added to the tuple as a single element
• Note that for a tuple, the new value is added as a single element TUPLE with a comma as (val,)
Tuple index System
• Tuples also follow an index system to access an element from the tuple
• The first element is given an index of 0 and the last element, an index of length-1
• With the negative index, the last element has a negative index -1 and first element –(length)
Example:
T = ( 6.2, 9.1, 5, 8.2, ‘ab’, 7 )
Length = total elements = 6
First element +ve index = 0
First element -ve index = -(len) = -6
Last element +ve index = (6-1) = 5
Last element -ve index = -1
Accessing an Element of a Tuple
Once you create a tuple, the individual elements of a tuple can be accessed using a pair of square brackets
(NOT ( ) brackets). The following examples will make this clear:

Examples of Tuple Slicing:


You can form a slice from elements of a tuple using the same rules for a list.

Some properties of Tuples:


You can add two tuples to create a new tuple using the + operator.

You can repeat a tuple multiple times using the * operator


You can repeat a tuple multiple times using the * operator

In-Built Tuple Manipulation functions & Methods


1. len( ): Returns the length of a tuple, i.e. the number of elements in the tuple.

2. index( ): Returns the index of the first matched item (given by user) from the tuple.
3. count( ): Counts number of occurrences of a value in a tuple and returns the count.

4. sum( ): The function finds the sum of the values in the tuple and returns the sum. Note: The tuple must have
all numeric values.

5. max( ): The function finds the maximum value in a tuple and returns the maximum. Tuple must have all values
of the same data type

6. min( ): The function finds the minimum values in a tuple and returns the minimum. Tuple must have all values
of the same data type

7. sorted( ): The function returns a sorted list of the specified iterable object like a tuple. You can specify the
ascending or descending order. Tuple must have all values of the same data type.

Concept of Tuple Unpacking


1. Creating a tuple from a set of values is called tuple packing
2. Similarly, creating individual values from a tuple’s elements is called tuple unpacking
3. The number of variables on the left side of the assignment operator must match the number of elements
in the tuple
Differences in Modifying List & Tuple Elements
4. As a List is mutable, you can modify any element of a list in place. The address will also remain the same
5. However, if you try to change an element of a tuple in place it will raise error

Creating a Tuple from User Inputs


6. The + operator is used normally to create a tuple from user inputs in the manner shown below:

Problems on Tuples
1. Program to find the mean of values in a tuple.

2. Program to check if a value is present in a Tuple or not.


3. Program to find the frequency of elements in a tuple.

4. Program to find the maximum value from a tuple

DICTIONARY type data:


Some General Properties of Dictionary:
• A dictionary is a mutable, unordered collection of key:value pairs (the elements), that associate keys to values
• The term mutable means the elements in a dictionary can be modified or changed in place without the
requirement to create a new dictionary
• The term unordered means the order in which you enter the key:value pairs in a dictionary may not be the
same as the order in which it is stored in memory or displayed
• The key:value pairs in a dictionary are separated by commas and put within a pair of curly brackets { }
• The keys in a dictionary must be unique and of immutable data type
• The values in a dictionary can be of any data type and non-unique
• Example of dictionaries: D1 = { 8 : 2.4, 3 : 9.2, 2 : 1.4 } , D2 = { ‘a’ : 6, ‘c’ : 2, ‘b’ : 2 }

Accessing Values from a Dictionary


• The values stored in a dictionary can be accessed using the dictionary name and putting the corresponding
key inside a pair of [ ] brackets
• Here the key functions similar to the index in a list. Whereas the index in a list is predefined and fixed,
however in a dictionary, you can define the keys as per your requirement
• You can access the values stored in a dictionary using the corresponding keys
• Along with the dictionary name, you have to put the key inside a pair of [ ] brackets to access the
corresponding value as shown below:
>>> D = { ‘a’ : 6, ‘c’ : 2, ‘b’ : 2 , ‘f’ : 1 , ‘g’ : 1 , ‘d’ : 4 }
>>> D[ ‘c’ ] #To access the value corresponding to the key 'c'
2
>>> D[ ‘a’ ] #To access the value corresponding to the key 'a'
6
Different ways of initialising/creating a Dictionary
• D={} print(D) → { } #Creates empty or null dictionary
• D = dict ( ) print(D) → { } #Null dictionary using dict( ) function
• D = { ‘Jan’ : 31 } print(D) → {‘Jan’:31} #Creates a dictionary with 1 element
• D = { ‘a’ : 3, ‘e’ : 5 } print(D) → {‘a’:3, ‘e’:5} #Creates dictionary with 2 elements
• D = dict ( molecule = ‘water’, atoms = 3 ) print(D) → { 'molecule': 'water’, 'atoms’: 3 }
#Creates new dictionary from variable & value pairs. Here the variable-name forms the keys and must be
string type data following identifier naming rules
• D = dict ( zip ( (‘molecule’, ‘atoms’), (‘water’, 3) ) ) print(D) → { 'molecule': 'water’, 'atoms’: 3 }
#Creates new dictionary using the zip() function. The keys and values are given as two tuples which form
the arguments of zip. Each key from the key-tuple gets combined with corresponding value from the value-
tuple to form a key:value pair. Hence number of keys and number of values must match.
• D = dict ( [ [‘molecule’, ‘water’], [‘atoms’, 3] ] ) OR
D = dict ( ( (‘molecule’, ‘water’), (‘atoms’, 3) ) ) print(D) → { 'molecule': 'water’, 'atoms’: 3 }
#Creates new dictionary from key:value pairs. The key:value pairs are given as elements of a nested
list/tuple. For n key:value pairs you need n number of list/tuples
Basic Dictionary Types
There are two categories of dictionaries:
• Type-1: A dictionary which stores different properties of same object
Example: {'name' : 'Aishik Das', 'dept' : 'Sales', 'salary' : 50000 }
#Dictionary storing different data of a single employee. Each key:value pair represents a different property
• Type-2: A dictionary which stores same property of different objects
Example: { 'H' : 1, 'He' : 2, 'Li' : 3, 'Be' : 4, 'B' : 5, 'C' : 6 }
#Dictionary storing the atomic symbol and atomic number of different elements from periodic table. Each
key:value pair represents the same property i.e. symbol:Atomic_Number

Creating a Dictionary with user Inputs: Creating a Type-1 Dictionary


You can create a dictionary by inputting the values from the user and assigning them to keys as shown below:
REMEMBER: You have to create a null
dictionary like D={ }, before you create
the key:value pairs
Creating a Dictionary with user Input and a LOOP: Creating a Type-2 Dictionary
You can create a dictionary with inputs from the user using a loop. This can be done only when storing similar
categories of data for each dictionary element.

Creating a Nested Dictionary with user Input and a LOOP


The following example stores the ID of students as the keys of a dictionary Stud. The corresponding value is stored
as a dictionary for every ID. The value dictionary stores the name, class and section of a student. The statement
for k in Stud will take out each key from the dictionary one at a time and store in the loop variable k, which can be
used to access the corresponding value, which in this case is also a dictionary.
Comparing Dictionaries
• As dictionaries are unordered sequence, hence these are compared based on key:value pairs
• The order in which the key:value pairs occur is not considered
• Only equality (==) and non-equality (!=) operators are used with dictionaries
• Other type of comparisons cannot be done on dictionaries
Examples:
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'b':7, 'c':5 } ) → True #As both dictionaries are identical
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'c':5, 'b':7 } ) → True #Both have same key:value pairs. Order does not matter
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'c':3, 'b':7 } ) → False #As different key:value pairs
>>> print ( { 'a':2, 'b':7, 'c':5 } != { 'a':2, 'c':3, 'b':7 } ) → True #As different key:value pairs

Dictionary Functions & Methods


1. len( ): Returns the length of a dictionary, i.e. the number of key:value pairs in the dictionary

2. clear( ): Used to empty the content of a dictionary and make it a null dictionary (address does not change)

3. get( ): Is used to return the value corresponding to a given key. In case the key is not present, you can put an
error message to display. This is unlike the normal way to display a value using a key, where Python shows
error if key is not present.

4. items( ): The method returns all the items in the dictionary as a sequence or iterable object of (key,value)
tuples (in no particular order)

We can use the concept of tuple unpacking to use two loop variables to extract the values from the tuples that
are part of the sequence.
5. keys( ): The method returns all the keys in a dictionary as a sequence of keys. You can extract the keys using a
loop from the iterative object.

6. values( ): The method returns all the values in a dictionary as a sequence. You can extract the values using a
loop from the iterative object.

7. update( ): The method merges the key:value pairs from a new dictionary into the original dictionary. The
process adds or replaces the key:values as required in the original dictionary.

The common elements 'e':5 and 'u':1 in D1 are updated by 'e':8 and 'u':3 in D2. The element 'y':1 which is not
present in D1 is getting added to D1 from D2. The other elements 'a':3, 'i':2 and 'o':2 remain as it is in D1.
8. fromkeys( ): Returns a dictionary with the specified keys and a specified value. Can be used to set a
given/common value for all the keys in a dictionary. The keys are provided as a tuple or list.

Example: The following example counts the vowels separately in a sentence. It uses the dictionary vowCount
for storing each individual count. The same starting count value 0 is assigned to all the keys using the
fromkeys() method.
9. copy( ): Returns a shallow copy of a dictionary.

Remember that in case the value is an immutable data type (int, float, string, tuple), then changes in original
will not affect the corresponding value in the copy. If the value is a mutable data type (list, dictionary), any
changes made in the original will affect the copy also.
10.pop(): You can delete a particular key:value from a dictionary using pop method. The value is returned by
pop(). You can insert an error message also.

You can define an error message for non-existent keys also

11.popitem( ): Remove the last item inserted from the dictionary, and returns it as a tuple
12.setdefault( ): The method returns the value of a key (if the key is in the dictionary). If the key is not present, it
inserts the key with a None value to the dictionary. In this way it is different from the get() method.

13.sorted( ): The function is used to sort a dictionary. You can sort by both keys and values. The function returns
a list with the sorted keys or values.

14.del command: You can delete a particular key:value from a dictionary using del command

You can delete the entire dictionary using del also:

15.max() and min(): These functions can be used to get the maximum and the minimum key from a dictionary

Nesting a Dictionary
The value part of the key of a dictionary can be a dictionary itself. The following example illustrates the operation.
The keys of the dictionaries are to be arranged from outside-in up to the innermost key to get the value
corresponding to the inner-most key.
Extracting the keys and values from the dictionary
We can extract the keys and values using the keys() and values() methods and convert them to lists.

Traversing a Dictionary
You can use a for loop to iterate through a dictionary. The for loop will take out the keys from the dictionary one
by one and store them in the loop variable k. So D[k] will give the corresponding value.

Updating existing elements in a dictionary


As a dictionary is mutable, you can change the value of a dictionary using the corresponding key of that value. The
address remains the same
Checking for an existing key in a dictionary
The membership operators in and not in can be used to check if a key is present in a dictionary or not.

Printing a dictionary using pretty printing method


The Pretty Printing method is used to print very large dictionaries in a readable manner. For that you will have to
import the json module and use the dumps() function of the json module. The indent value indicates how much
space is to be kept from the left margin. It can be 1, 2, 3, 4, etc.

Dictionary Problems:
1. Write a program to find the frequency of different alphabets in a string input by the user.

2. Given two dictionaries D1 and D2, write a program to list the overlapping keys of the two dictionaries

P.T.O.
3. Store a set of item and prices in a dictionary

4. Write a program to exchange the key:value pairs and form a new dictionary where the keys of the first
dictionary become the values of the second dictionary, and the values become the keys.

5. Create a LIST, where each element of the list is a DICTIONARY. Each dictionary stores the Name, Class, and
Section of a student. After the entire data is input from the user for a given number of students, the program
displays the data for students of class 12.
6. Find the maximum value stored against a key in the dictionary.

7. To display/access dictionary data in ascending order of keys

Using Modules in Python


Concept of importing a Module:
• When a common category of functions, constants, and other related items are put into a file and stored for
use by other programs, then such a file is called a module.
• Once you import a given module in your program, you can then use all the functions, constants etc. inside the
module in your program.
• You can import the content of a module into your program in 2 different ways:
o METHOD-1: The following format allows you to import the content of entire modules:
▪ import module1, module2, module3, …
▪ Example: import math #imports the entire math module
import random, statistics #mports the entire random and statistics module
o METHOD-2: In case the content of the entire module is not required, then one can selectively import part
of a module also. The following syntax shows how to do this:
▪ from module import object_name1, object_name2, …
▪ Example: from math import floor, ceil #imports only the floor and ceil functions

Using the Functions and Constants in a Module:


Depending upon the way you use the import statement, the process of accessing a function or a constant from the
module is different. Hence depending upon the Method-1 or the Method-2 that you have used to import a module,
the syntax for accessing the functions and constants are given below:
When using Method-1
• Once you import a module using the import module format, then to use any function from the module you
have to prefix each function in the module with the module name
• The following example uses the sqrt( ) function and pow( ) function of the math module.
When using Method-2
• Once you import a module using the from module import format, then to use a function from the module you
have to simply write the function name without attaching the module name
• For example, to import a single object like the value of the constant pi or a single function like sqrt() from the
math module you can write the following:

CAUTION: While importing an object using a from statement, DO NOT USE the module name with the
imported object name. It will produce ERROR

Importing Multiple Objects from Modules


• To import all the items from a module, so that you don’t have to prefix the module’s name you can write:
o from <module_name> import *
• Hence, to import all the items from the math module you use a * and can write:
o from math import * #imports all the functions and constants into your program
• Once this is done, you can use all the items of the math module, without the need to add the module name
math as a prefix
o print ( cos (3.2) ) #Should not be writing math.cos(3.2)
o print ( exp (2) ) #Should not be writing math.exp(2)
Functions and Constants from the math module
Before using any math module function, import the module by a statement: import math
Functions from the random module
The random module in Python has functions to generate random numbers. Some of these functions are:
random() function
• Returns a random floating point number N in the range [ 0.0, 1.0 ) i.e. 0.0 <= N < 1.0
• The value can be 0.0 but is always less than 1.0
• Hence probable outputs of the following code can be: random.random( )
o 0.0
o 0.1235
o 0.9
o 0.99999999

randint() function
• randint ( a, b ) : Returns a random integer N in the range [ a , b ] i.e. a <= N <=b
• Probable outputs of the following code can be: random.randint (3, 6)
o 3
o 4
o 5
o 6

randrange() function
• Returns a random number in range, where the number generated is from a start-value and goes up to one
less than stop-value, in steps of the step-value ( start, stop, step )
• The function can take from 1 to 3 arguments.
• All arguments must be integer values
• The different options are shown below:
One argument randrange() function:
• One argument (default starts at 0, stops at 1 less than stop value, step is 1):
random.randrange ( stop )
Probable outputs for: random.randrange (5)
o 0
o 1
o 2
o 3
Two argument randrange() function:
• Two arguments (starts from start, stops at 1 less than stop value, step is 1):
random.randrange ( start, stop )
Probable outputs for: random.randrange (2, 6)
o 2
o 3
o 4
o 5
Three argument randrange() function:
• Three arguments (starts from start, stops at 1 less than stop value, step is step):
random.randrange ( start, stop, step )
Probable outputs for: random.randrange (-10, -35, -5)
o -10
o -15
o -20
o -25
o -30
Functions from the statistics module
• The statistics module in Python provides many statistics related functions
• To use these functions first import the statistics module: import statistics
• The different functions under this module are:
mean( ) function:
• Returns the average value of the sequence of values passed to it:
o x = statistics.mean ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] )
o print ( x ) → 4.375
median( ) function:
• Returns the middle value of the sequence of values passed to it.
• Before calculating the median, Python sorts the data in the list/tuple in ascending order
• Two possibilities are there:
o If number of values n in list is odd, then Median = (n+1)/2 th term
▪ x = statistics.median( [3, 9, 5, 7, 1, 4, 2] ) #sorted list = [1, 2, 3, 4, 5, 7, 9]
▪ print(x) → 4 #Result is 4

o If number of values n in list is even, then Median = [ (n/2)th term + (n/2+1)th term ] /2
▪ y = statistics.median ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] ) #sorted list = [1, 3, 3, 3, 4, 5, 8, 8]
▪ print ( y ) → 3.5 #Result is (3+4)/2
mode( ) function:
• Returns the most often repeated value of sequence of values passed
o z = statistics.mode ( [ 5, 8, 3, 4, 8, 3, 1, 3 ] )
o print ( z ) → 3
• Returns the first most often repeated value of sequence of values passed, in case more than one values have
the highest frequency
o w = statistics.mode ( [ 5, 8, 8, 4, 3, 8, 3, 1, 3 ] )
o print ( w ) → 8 #Here both 8 and 3 have same highest frequency of 3. Hence the first value
from the left with the highest frequency i.e. 8 is returned

Society, Law and Ethics


• Cyber Safety: It refers to the safe and responsible use of the Internet to ensure safety and security of
personal information and not posing threat to someone else’s information.
• Identity Theft: It is the theft of personal information like name, login details etc. in order to commit fraud like
stealing money or gain other benefits.
• Cyber Crime: Any criminal offence that is facilitated by or involves the use of electronic communication or
information systems including electronic devices, computer, or the Internet is referred to as Cyber Crime.
• Cyber Bullying: A form of bullying or harassment using electronic means like online social platforms. It
involves harassing, demeaning, embarrassing, defaming or intimidating someone using modern technology like
the Internet
• Cyber Trolling: Derogatory message or comments posted online, targeting people
• Cyber Stalking: A form of online harassment wherein the victim is subjected to a horde of online messages
and emails. The victim is stalked online using various online social sites as an anonymous person.
• Intellectual Property Rights (IPR): These are the rights of the owner of information to decide how much
information is to be exchanged, shared or distributed and also the price for doing this.
• Digital Property: Digital Property/Assets refers to any information about you or created by you that exists in
digital form, either online or on an electronic storage.
• Digital Certificate: Digital Certificate is used to encrypt online data communication between a browser and a
web-site. After verifying that a company owns a website, certification authority signs a certificate trusted by
the internet browsers.
• Digital Signature: It is a way to authenticate the identity of the creator of a digital content. It has the same
legal authority for online buying/selling or signing legal contracts.
• Computer Virus: These are malicious codes and programs that cause damage to data and files on a system.
These can attack any part of a computer’s software like the boot area, operating system, files, and application
programs.
• Malware: A general term used to refer to viruses, worms, spyware, adware, etc. i.e. any unwanted software
that someone else runs on your computer.
• Worm: A self-replicating program which eats up the entire disk space or memory. It keeps creating copies of
itself
• Trojan: A program that appears harmless but actually performs malicious jobs like deleting/damaging files
• Phishing: It is the practice of attempting to acquire sensitive information from individuals over the Internet
by means of deception. The imposter uses an authentic looking email or website to mislead the recipient into
sharing his/her sensitive personal information.
• Pharming: The hacker tries to redirect a website’s traffic to another fraud or useless website. The attacker
convinces the site to be real and takes your personal information that you enter
• Eavesdropping: Unauthorised monitoring of other people’s communications. The attacker listens to the
communication and gets information about the content of the message. If message is not encrypted or digital
signature is not used, the attacker can use these loopholes to modify the message and send it to the recipient.
• Computer Forensic: It refers to the methods used for interpretation of computer media for digital evidence.
• Cyber Law: It is a generic term which refers to all the legal and regulatory aspects of the Internet and the
World Wide Web.
• India’s IT Act: In India the Cyber Laws were enforced through the Information Technology Act 2000. It’s
prime purpose is to provide legal recognition to electronic commerce and to facilitate filing of electronic
records with the Government, i.e. to provide legal infrastructure for ecommerce in India.
• Spyware: Software installed in your computer to spy on your activities. The data is then reported to people
who pay for it. Spyware get installed in your computer without your consent and normally gets downloaded
into your computer when you are visiting a particular website
• Adware: Programs that deliver unwanted ads to your computer and consume the network bandwidth. Unlike
Spyware, Adware may get installed in your computer with your consent.
• Spamming: Messaging systems to send unsolicited messages to a large number of recipients for commercial
advertising.
• Cookies: A small piece of data sent from a website and stored in the user’s browser while a user is browsing
the net. It is used for storing information related to your online habits.
• Different Ways Websites Track You:
o Sharing your IP address
o Using Cookies: To store your preferences and online habits
o HTTP Referrer: When clicking a hyperlink, the browser provides that link with your IP address, and other
information about your machine
o User Agent: Sent by your browser to a website with information regarding your browser and operating
system
• Ways of Preventing Theft of Personal Information:
o Anonymous Browsing: These browsers allow users to view websites anonymously i.e. without revealing
any personal information of the user, like the user’s IP address, machine type, location etc. Example, Tor,
Epic etc.
o Private Browsing: It is a type of browsing where a browser opens in an incognito mode or through proxy
or VPN. It does not store cookies about your online activities.
o A VPN or Virtual Private Network is a method used to add security and privacy when using public
networks. VPNs encrypt your internet traffic and disguise your online identity. Then prevents third parties
to track your activities online and steal your data
• Ways to ensure Confidentiality of Personal Information:
o Use Firewall: A Firewall is an application program that monitors all incoming and outgoing network traffic
and prevents all unauthorised data packets.
o Control Browser Setting: Adjust browser settings to exclude cookies as these can be used to build up
detailed profiles of your surfing habits
o Browse Privately: Wherever possible, browse the Internet privately. This prevents websites from storing
cookies on your computer
o Carefully Handle Emails: Do not open mails or mail attachments from an unknown sender. Try not to click
on links to websites in emails
o Do not give Sensitive Information: Try not to provide sensitive information through wireless connections
(like WiFi) available free at a public place
• Damages caused by Viruses:
o Damage or Delete Files: Viruses can damage or delete random documents or specific files important for
your operating system
o Slow Down Your Computer: Viruses can run in the background and cause your computer to slow down
o Invade Email Application: Some viruses can infect your mailing app and spread through the contacts in
your mailing list
• Damages Caused by Adware:
o Track Information like Spyware
o Display Annoying Advertising
o Slow down your Computer
• Damages caused by Spamming:
o Spam Reduces Productivity: Legitimate email delivery may get hampered by the millions of spam emails
that may circulate in the network
o Eats up your Time: Deleting Spam Messages can take a long time
o Spread Viruses: Spam mails may contain fraudulent material and even used to spread viruses
• Various threats to Computer Security can be minimized or eliminated by:
o Active Protection: To install an anti-virus software with Internet security that deals with viruses, spyware,
and intrusion
o Preventive Measures: Should try to prevent these issues from arising at all
• Some Active Protection Measures:
o Install Anti-Virus and Anti-Spyware software to detect and eliminate any malware that sneaks into your
computer
o Use Sender Filtering to allow only messages from your approved sender list to reach your inbox. All other
mails will get quarantined for later review. This will reduce spamming
o Use Digital Certificate to verify the identity of the message-sender to the recipient.
o Use Digital Signature to authenticate the identity of the creators and producers of digital information. This
helps prevent fraud during buying/selling
o Keyword Filtering can be used to filter out email messages that contain certain unwanted keywords or
phrases as defined by you.
o Install Anti-Virus and Anti-Spyware software to detect and eliminate any malware that sneaks into your
computer
o Use Sender Filtering to allow only messages from your approved sender list to reach your inbox. All other
mails will get quarantined for later review. This will reduce spamming
o Use Digital Certificate to verify the identity of the message-sender to the recipient.
o Use Digital Signature to authenticate the identity of the creators and producers of digital information. This
helps prevent fraud during buying/selling
o Keyword Filtering can be used to filter out email messages that contain certain unwanted keywords or
phrases as defined by you.
• Some Passive Protection Measures:
o Keep your System Up to Date to reduce security holes in operating systems and software programs
o Use Caution when Downloading Files from the Internet. Download files from reliable or authorized sites
only
o Be Careful with Email and do not download and open unsolicited emails or attachments to emails
o Disable Cookies if possible, for the safety of your personal information on the Internet
o Use Encrypted Connection when providing sensitive information (like using https).
o Avoid Online Transactions from a public WiFi network
• A Firewall
• It is a Network Security System, either hardware or software-based that controls the incoming or outgoing
network traffic based on a set of rules. Two types of Firewalls are:
o Software Firewall: It is a special type of software running on a computer. It provides protection to
outside attempts to control or gain access to your computer. It can prevent access to trojans and
worms.
o Hardware Firewall: It is a physical device that can perform the work of a software firewall. It can be a
dedicated computer that helps to protect every computer in a network from outside various attacks.

You might also like