Abps, Awarpur Class Xii - Study Material 2025-26
Abps, Awarpur Class Xii - Study Material 2025-26
1
Computer Science (2025-26) CLASS
XII Code No. 083
Unit wise Syllabus
Unit 1: Computational Thinking and Programming – 2
● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user defined functions),
creating user defined function, arguments and parameters, default parameters, positional parameters,
function returning value(s), flow of execution, scope of a variable (global scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a file using
with clause, writing/appending data to a text file using write() and writelines(), reading from a text file
using read(), readline() and readlines(), seek and tell methods, manipulation of data in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab, ab+), close a
binary file, import pickle module, dump() and load() method, read, write/create, search, append and
update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using writer(),writerow(),writerows()
and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack using list.
Unit 2: Computer Networks
● Evolution of networking: introduction to computer networks, evolution of networking
(ARPANET, NSFNET, INTERNET)
2
PYTHON REVISION TOUR
ABOUT PYTHON:
1. Python is a high-level programming language developed by Guido Van Rossum. The language was
released in February 1991 and got its name from a BBC comedy series “Monty Python’s Flying
Circus”.
2. It is an interpreted and platform independent language i.e. the same code can run on any operating
system.
3. It can be used to follow both procedural and object-oriented approaches to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.
BASIC TERMS USED IN PYTHON:
1. Token / Lexical Unit: The smallest individual unit in a python program is known as Token or Lexical
Unit. A token has a specific meaning for a python interpreter. Examples of tokens are: Keywords,
Identifiers, Literals, Operators and Punctuators.
3
2. Keywords: Keywords are the reserved words and have special meaning for Python Interpreters.
Each keyword can be used only for that purpose which it has been assigned. Examples: and, while,
del, with, True, None, False, return, try etc.
3. Identifiers: These are the names given to variables, objects, classes or functions etc. there are
some predefined rules for forming identifiers which should be followed else the program will raise
Syntax Error.
4. Literals: The data items that have a fixed value are called Literals. If a data item holds numeric
values it will be known as Numeric Literal, if it contains String values it will be known as String Literal
and so on. It means the type of value stored by the data item will decide the type of Literal. Python
has one special literal which is None to indicate absence of value.
5. Operators: These are the symbols that perform specific operations on some variables. Operators
operate on operands. Some operators require two operands and some require only one operand to
operate. The operator precedence in Python is as follows:
NOTE: When we compare two variables pointing to same value, then both Equality (==) and identity
(is) will return True. But when same value is assigned to different objects, then == operator will return
True and is operator will return False.
6. Punctuators: These are the symbols that are used to organize sentence structure in programming
languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () , .
7. Variables: In Python, variables are not storage containers like other programming languages. These
are the temporary memory locations used to store values which will be used in the program further.
Each time we assign a new value to a variable it will point to a new memory location where the
assigned value is stored. In Python we do not specify the size and type of variable, besides these are
decided as per the value we assign to that variable.
8. Data Type: It specifies the type of data we will store in the variable according to which memory will
be allocated to that variable and it will also specify the type of operations that can be performed on
that variable. Examples: integer, string, float, list etc.
4
9. Dynamic Typing: It means that it will be decided at the run time that which type of value the
variable will store. It is also called implicit conversion. For example,
Here, we need not to specify the type of value a will store besides we can assign any type of value to a
directly. Similarly, the data type of c will be decided at run time on the basis of value of a and b.
10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly by using
some built-in functions. Here, we can say that we force the variable by applying a built-in function to
change the data type and it is not done at run time. Some common type casting functions are int(),
float(), str(), list(), tuple(), dict() etc.
Data types are classified in two basic categories: Mutable data types and Immutable data types.
Mutable data types are those data types whose value can be changed without creating a new object.
It means mutable data types hold a specific memory location and changes are made directly to that
memory location. Immutable data types are those data types whose value cannot be changed after
they are created. It means that if we make any change in the immutable data object then it will be
assigned a new memory location.
1. In Numeric data types, Integers allow storing whole numbers only which can be positive or negative.
Floating point numbers are used for storing numbers having fractional parts like temperature, area
etc. In Python, Floating point numbers represent double precision i.e. 15-digit precision. Complex
numbers are stored in python in the form of A + Bj where A is the real part and B is the imaginary part
of complex numbers.
5
2. Dictionary is an unordered set of commas separated values where each value is a key: value pair.
We represent the dictionary using curly brackets {}. Keys in the dictionary should be unique and they
cannot be changed while values of the keys can be changed.
3. Boolean allows storing only two values True and False where True means 1 and False means 0
internally.
4. Sequence data types store a collection or set of values in an ordered manner. We can traverse the
values/elements using indexing.
A. STRING:
Introduction: String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be created by enclosing
one or more characters in single, double or triple quote.
Indexing: Each individual character in a string can be accessed using a technique called indexing. The
index specifies the character to be accessed in the string and is written in square brackets ([ ]). The
index of the first character (from left) in the string is 0 and the last character is n-1 where n is the
length of the string.
String operations:
(i) Concatenation: To concatenate means to join. Python allows us to join two strings using
concatenation operator plus which is denoted by symbol +.
'HelloWorld!'
(ii) Repetition: Python allows us to repeat the given string using repetition operator, which is denoted
by symbol *.
'HelloHello'
6
(iii) Membership: Python has two membership operators 'in' and 'not in'. The 'in' operator takes two
strings and returns True if the first string appears as a substring in the second string, otherwise it
returns False.
True
False
(iv) Slicing: In Python, to access some part of a string or substring, we use a method called slicing.
This can be done by specifying an index range. Given a string str1, the slice operation str1[n:m]
returns the part of the string str1 starting from index n (inclusive) and ending at m (exclusive). In other
words, we can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1]. The
numbers of characters in the substring will always be equal to difference of two indices m and n,
i.e., (m-n).
W
o
r
l
d
!
In the above code, the loop starts from the first character of the string str1 and automatically
ends when the last character is accessed.
7
>>> str1 = 'Hello World!'
index += 1
Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.
viii. endswith(): Returns True if the given string ends with the supplied substring otherwise returns
False.
>>> str1 = 'Hello World!'
>>> str1.endswith('World!')
True
>>> str1.endswith('!')
True
>>> str1.endswith('lde')
False
ix. startswith(): Returns True if the given string starts with the supplied substring otherwise returns
False
>>> str1 = 'Hello World!'
>>> str1.startswith('He')
True
>>> str1.startswith('Hee')
False
x. isalnum(): Returns True if characters of the given string are either alphabets or numeric. If
whitespace or special symbols are part of the given string or the string is empty it returns False.
>>> str1 = 'HelloWorld'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False
xi. islower(): Returns True if the string is non-empty and has all lowercase alphabets, or has at least
one character as lowercase alphabet and rest are non-alphabet characters
>>> str1 = 'hello world!'
>>> str1.islower()
True
>>> str1 = 'hello 1234'
>>> str1.islower()
True
>>> str1 = 'hello ??'
>>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False
>>> str1 = 'Hello World!'
>>> str1.islower() False
9
xii. isupper(): Returns True if the string is non-empty and has all uppercase alphabets, or
has at least one character as uppercase character and rest are non-alphabet characters
>>> str1 = 'HELLO WORLD!'
>>> str1.isupper()
True
>>> str1 = 'HELLO 1234'
>>> str1.isupper()
True
>>> str1 = 'HELLO ??'
>>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False
>>> str1 = 'Hello World!'
>>> str1.isupper()
False
xiii. isspace(): Returns True if the string is non-empty and all characters are white spaces
(blank, tab, newline, carriage return)
>>> str1 = ' \n \t \r'
>>> str1.isspace()
True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False
xiv. istitle(): Returns True if the string is non-empty and title case, i.e., the first letter of every
word in the string in uppercase and rest in lowercase.
>>> str1 = 'Hello World!'
>>> str1.istitle()
True
>>> str1 = 'hello World!'
>>> str1.istitle()
False
xv. lstrip(): Returns the string after removing the spaces only on the left of the string
>>> str1 = ' Hello World! '
>>> str1.lstrip()
'Hello World! '
xvi. rstrip(): Returns the string after removing the spaces only on the right of the string
>>> str1 = ' Hello World!'
>>> str1.rstrip()
' Hello World!'
xvii. strip(): Returns the string after removing the spaces both on the left and the right of the string
>>> str1 = ' Hello World!'
>>> str1.strip()
'Hello World!'
xviii. replace(oldstr, newstr): Replaces all occurrences of old string with the new string >>> str1
= 'Hello World!'
10
>>> str1.replace('o','*')
'Hell* W*rld!'
>>> str1 = 'Hello World!'
>>> str1.replace('World','Country')
'Hello Country!'
>>> str1 = 'Hello World! Hello'
>>> str1.replace('Hello','Bye')
'Bye World! Bye'
xix. join(): Returns a string in which the characters in the string have been joined by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
xx. partition()): Partitions the given string at the first occurrence of the substring
(separator) and returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator If the separator is not found in the string, it returns the
whole string itself and two empty strings
xxi. split(): Returns a list of words delimited by the specified substring. If no delimiter is
given then words are separated by space.
>>> str1 = 'India is a Great Country'
>>> str1.split()
['India','is','a','Great', 'Country']
>>> str1 = 'India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
SUMMARY
A string is a sequence of characters enclosed in single, double or triple quotes.
Indexing is used for accessing individual characters within a string.
The first character has the index 0 and the last character has the index n-1 where n is the length
of the string. The negative indexing ranges from -n to -1.
Strings in Python are immutable, i.e., a string cannot be changed after it is created.
Membership operator in takes two strings and returns True if the first string appears as a substring
in the second else returns False. Membership operator ‘not in’ does the reverse.
Retrieving a portion of a string is called slicing. This can be done by specifying an index range.
The slice operation str1[n:m] returns the part of the string str1 starting from index n (inclusive)
and ending at m (exclusive).
Each character of a string can be accessed either using a for loop or while loop.
There are many built-in functions for working with strings in Python.
11
B. LIST:
Introduction:
The data type list is an ordered sequence which is mutable and made up of one or more elements.
Unlike a string which consists of only characters, a list can have elements of different data types,
such as integer, float, string, tuple or even another list. A list is very useful to group together
elements of mixed data types. Elements of a list are enclosed in square brackets and are separated
by comma. Like string indices, list indices also start from 0.
Indexing: The elements of a list are accessed in the same way as characters are accessed in a string.
List operations (concatenation, repetition, membership & slicing):
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by the symbol +.
>>> list1 = [1,3,5,7,9] #list1 is list of first five odd integers
>>> list2 = [2,4,6,8,10] #list2 is list of first five even integers
>>> list1 + list2 #elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
Repetition
Python allows us to replicate a list using repetition operator depicted by symbol *.
>>> list1 = ['Hello'] #elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
Membership
Like strings, the membership operators in checks if the element is present in the list and
returns True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
Traversing a list using loops:
We can access each element of the list or traverse a list using a for loop or a while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Red
Green
Blue
Yellow
Black
12
Built-in functions:
i. len(): Returns the length of the list passed as the argument. Creates a list if a sequence is
passed as an argument
>>> list1 = [10,20,30,40,50]
>>> len(list1)
5
ii. list(): Creates an empty list if no argument is passed
>>> list1 = list()
>>> list1
[]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']
iii. append(): Appends a single element passed as an argument at the end of the list
The single element can also be a list
>>> list1 = [10,20,30,40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
iv. extend(): Appends each element of the list passed as argument to the end of the given list
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
v. insert(): Inserts an element at a particular index in the list
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
vi. count(): Returns the number of times a given element appears in the list
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0
vii. index(): Returns index of the first occurrence of the element in the list. If the element
is not present, ValueError is generated
>>> list1 = [10,20,30,20,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list
13
viii. remove(): Removes the given element from the list. If the element is present multiple
times, only the first occurrence is removed. If the element is not present, then ValueError
is generated
>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x not in list
ix. pop(): Returns the element whose index is passed as parameter to this function and also
removes it from the list. If no parameter is given, then it returns and removes the last
element of the list
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
x. reverse(): Reverses the order of elements in the given list
>>> list1 = [34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']
xi. sort(): Sorts the elements of the given list in-place
>>> list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
xii. sorted(): It takes a list as parameter and creates a new list consisting of the same
elements arranged in sorted order
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
xiii. min() / max() / sum(): Returns smallest / largest / sum of elements of the list
>>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12 >>> max(list1) 92 >>> sum(list1) 284
14
SUMMARY
Lists are mutable sequences in Python, i.e., we can change the elements of the list.
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created. An attempt to do this would lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
Tuple operations:
Concatenation
Python allows us to join tuples using concatenation operator depicted by symbol +. We can also
create a new tuple which contains the result of this concatenation operation.
Repetition
Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can
repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the
second operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
15
Membership
The in operator checks if the element is present in the tuple and returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
Built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), sum() work same as list.
SUMMARY
• Tuples are immutable sequences, i.e., we cannot change the elements of a tuple once it
is created.
• Elements of a tuple are put in round brackets separated by commas.
• If a sequence has comma separated elements without parentheses, it is also treated as a tuple.
• Tuples are ordered sequences as each element has a fixed position.
• Indexing is used to access the elements of the tuple; two-way indexing holds in dictionaries as in
strings and lists.
• Operator ‘+’ adds one sequence (string, list, tuple) to the end of other.
• Operator ‘*’ repeats a sequence (string, list, tuple) by specified number of times
• Membership operator ‘in’ tells if an element is present in the sequence or not and ‘not in’ does
the opposite.
• Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), max(),sum().
D. Dictionary:
Introduction:
The data type dictionary falls under mapping. It is a mapping between a set of keys and a set of
values. The key-value pair is called an item. A key is separated from its value by a colon (:) and
consecutive items are separated by commas. Items in dictionaries are unordered, so we may not
get back the data in the same order in which we had entered the data initially in the dictionary.
Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in curly braces.
Each item is a key value pair, separated through colon (:). The keys in the dictionary must be
unique and should be of any immutable data type, i.e., number, string or tuple. The values can be
repeated and can be of any data type.
16
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
Mutability of dictionary (adding a new item, modifying an existing item): Dictionaries are mutable
which implies that the contents of the dictionary can be changed after it has been created.
Adding a new item
We can add a new item to the dictionary as shown in the following example: >>>
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-value pair.
Example to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
#Change marks of Suhel to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
Membership
The membership operator in checks if the key is present in the dictionary and returns True, else it
returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
The not in operator returns True if the key is not present in the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a dictionary:
We can access each item of the dictionary or traverse a dictionary using for loop.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Method 1
>>> for key in dict1:
print(key,':',dict1[key])
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
>>> for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
17
Built-in functions: len(), dict(), keys(), values(), items(), get(), update(), del, clear(),
fromkeys(),copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted(), copy();
keys() Returns a list of keys in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
the dictionary >>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])
values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
the dictionary >>> dict1.values()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples (key – >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
value) pair >>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92),
('Sangeeta', 85)])
update() appends the key-value pair >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
of the dictionary passed as >>> dict2 = {'Sohan':79,'Geeta':89}
the argument to the key- >>> dict1.update(dict2)
value pair of the given >>> dict1
dictionary {'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85,
'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
18
del() Deletes the item with >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
the given key to delete 'Sangeeta':85}
the dictionary from the >>> del dict1['Ram']
memory we write: >>> dict1
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1
NameError: name 'dict1' is not defined
• Dictionary is a mapping (non-scalar) data type. It is an unordered collection of key value pair; key
value pair is put inside curly braces.
• Each key is separated from its value by a colon.
• Keys are unique and act as the index.
• Keys are of immutable type but values can be mutable.
QUESTIONS:
1. What will be the output of the following expression?
float(5 + int(4.39 + 2.1) % 2)
a. 5.0 b. 5 c. 8.0 d. 8
2. What is the value of this expression?
3*1**3
a. 27 b. 9 c. 3 d. 1
3. What can be a possible output at the time of execution of the program from the
following code? import random
AR = [20,30,40,50,60,70];
FROM =
random.randint(1,3) TO =
random.randint(2,4) for K
in range(FROM,TO+1):
print (AR[K],end=”# “)
4. Assertion (A): append() and extend() are both methods to insert elements in a list.
Reason (R): While append() adds elements at the end of the list, extend can add elements
anywhere in the list.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
5. Assertion (A): A dictionary cannot have two same keys with different values.
Reason (R): Keys of a dictionary must be unique.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
FILL IN THE BLANKS.
21
FUNCTION
A function is a programming block of codes which is used to perform a single, related, specific task. It
only works when it is called. We can pass data, known as parameters, into a function. A function can
return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and other objects
are of same significance. Functions can be assigned to variables, stored in collections, or passed as
arguments. This brings additional flexibility to the language.
Advantages of Functions
Reducing duplication of code
Decomposing complex problems into simpler pieces
Improving clarity of the code
Reuse of code
Information hiding
Python function types
There are three categories of functions:
Built-in functions
Function defined in modules
User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in
functions. The python interpreter has several such functions that are always available for
use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific module
is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is the most
important feature in Python that consists of custom-defined logics with a set of rules and regulations
that can be passed over the data frame and used for specific purposes.
Internally Python names the segment with top-level statements (no indentation) as _main_ Python
begins execution of a program from top-level statements.
22
Defining a Function
[“ ” ”<function’s docstring>” “ “]
<statements> [<statements>]
……………………..
A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).
Function header:
The Header of a function specifies the name of the function and the name of each of its parameters. It
begins with the keyword def.
Parameters:
Variables that are listed within the parenthesis of a function header.
Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)
Flow of execution in a function call
The flow refers to the order in which statements are executed during a program run. The function
body is a block of statements and python executes every block in an execution frame.
23
An execution frame contains:
Some internal information (used for debugging)
Name of the function
Values passed to the function
Variables created within the function
Information about the next instruction to be executed
Whenever a function call statement is encountered, an execution frame for the function is created and
the control is transferred to it. The statements are then executed and if there is return statement in the
program, it will be executed and returns to the function call statement block.
def message():
def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))
# main program
sum(10,20)
In the above program, two functions message() and sum() is declared. The message() function does
not accept any argument but displays a text on the screen whenever we call it. On the other hand, the
sum() function accept two arguments and display their sum on the screen. When the main program
calls the function message(), the program flow goes to the body of the function message() and
execute its codes. After that, it returns to the main program and then calls the second function sum()
by sending it two arguments (10,20), the program flow goes to the body of the function sum(), and
execute its code and again returns to the main program. At last, the main programs end.
The function calling another function is called the caller and the functions being called is the called
function or callee.
The parameters are the variables that we can define in the function declaration. In fact, we utilized
these variables within the function. Also, the programming language in the function description
determines the data type specification. These variables facilitate the function’s entire execution. In
addition, they are known as local variables because they are only available within the function.
The arguments are the variables given to the function for execution. Besides, the local variables of the
function take the values of the arguments and therefore can process these parameters for the final
output.
24
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as define in
the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z) #3 values(all variables) passed
check(2,x,y)
#3values(literal+variables)passed check ( 2 , 3
, 4 ) # 3 values ( all literal ) passed. Thus
through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)
2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal, time, rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400, time get 2 and since the third argument rate is missing,
so default value 0.10 is used for rate.
Default arguments are useful in situations where some parameters always have same value.
Some advantages of the default parameters are listed below:-
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.
3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the function call
statement.
Example:-
25
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
And argument list must first contain positional(required) arguments followed by any keyword
argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
Remember: The variable in main program is differ from the variable in function definition i.e. a and b
should be x and y. In this scenario the variable passed (num1, num2) will be called argument, and
when it replace with the variable defined in the function will be called as parameter.
Note: As return does not show the result we have to store the returned value on another
variable x.
def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!
Returning a Function
If you wish to return some values from the function to the rest of the program, you can use the return
statement. As the name suggests, it returns a value without printing it. Executing this statement will
cause the Python function to end immediately and store the value being returned into a variable.
27
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible or
known. In python there are broadly 2 kinds of Scopes:
Global Scope
Local Scope
Global Scope:
A name declared in top level segment (_main_) of a program is said to have global scope and
can be used in entire program.
Variable defined outside of the all functions are global variables.
Local Scope:
A name declared in a function body is said to have local scope i.e. it can be used only within
this function and the other block inside the function.
The formal parameters are also having local scope.
When dealing with Python functions, you should also consider the scope of the variables. The code in
a function is in its own little world, separate from the rest of the program. Any variable declared in the
function is ignored by the rest of the function. This means that two variables with the same name can
exist, one inside the function and the other outside the function. However, this is not a good practice.
All variable names must be unique regardless of their scope.
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:
Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime is entire
program run i.e. as long as program is executing. For local variable, lifetime is their function’s run i.e.
as long as function is executing.
28
Name Resolution (Scope Resolution)
For every name used within program, python follows name resolution rules known as LEGB rule.
Local Environment : first check whether name is in local environment, if yes Python uses its
value otherwise moves to (ii)
Enclosing Environment: if not in local, Python checks whether name is in Enclosing Environment, if
yes Python uses its value otherwise moves to (iii)
Global Environment: if not in above scope Python checks it in Global environment, if yes Python uses
it otherwise moves to (iv)
Built-In Environment: if not in above scope, Python checks it in built-in environment, if yes, Python uses
its value otherwise Python would report the error: name <variable> notdefined.
RANDOM MODULE
value
Q1 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the minimum values that can be assigned to each of
the variables BEGIN and LAST.
import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3)
LAST = random.randint(2, 4)
for I in range (BEGIN, LAST+1):
print (VALUES[I], end = "-")
Q2 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables FROM and TO.
Ans
Maximum value of FROM = 3
Maximum value of TO = 4
29
(ii) 30#40#50#
Q3 Consider the following code: import math import random
print(str(int(math.pow(random.randint(2,4),2))))
print(str(int(math.pow(random.randint(2,4),2))))
print(str(int(math.pow(random.randint(2,4),2))))
What could be the possible outputs out of the given four choices?
i) 2 3 4 ii) 9 4 4 iii)16 16 16 iv)2 4 9
Ans
Possible outputs : ii) , iii)
randint() will generate an integer between 2 to 4 which is then raised to power 2, so possible
outcomes can be 4,9 or 16
Q4 Consider the following code and find out the possible output(s) from the options given below.
Also write the least and highest value that can be generated.
import random as r
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20
ii) 23 27 22 20 iv) 21 25 20 24
Ans
Possible outputs : i), iii) and iv)
Least value : 10
Highest value : 15
Q5 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables BEG and END.
import random
heights=[10,20,30,40,50]
beg=random.randint(0,2)
end=random.randint(2,4)
for x in range(beg,end):
print(heights[x],end=’@’)
Q6 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code?
Import random
Ar=[20,30,40,50,60,70]
From =random.randint(1,3)
To=random.randint(2,4)
30
for k in range(From,To+1):
print(ar[k],end=”#”)
(i) 10#40#70# (iii) 50#60#70# (ii) 30#40#50# (iv) 40#50#70#
Q7 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code. Select which option/s is/are correct?
import random
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' )
print((100) -random.randint(15,25) , end = ' ' ) print((100)
*random.randint(15,25) )
(i) 15 122 84 2500 (ii) 21 120 76 1500 (iii) 105 107 105 1800 (iv) 110 105 105 1900
WORKSHEET
Questions (1 mark)
1. Which of the following is the use of function in python?
• Functions are reusable pieces of programs
• Functions don’t provide better modularity for your application
• you can’t also create your own functions
• All of the mentioned
2. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, ‘is maximum’)
elif a == b:
print(a, ‘is equal to’, b)
else:
print(b, ‘is maximum’)
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
3. What is the output of the below program?
def C2F(c):
return c * 9/5 + 32
print (C2F(100))
print (C2F(0))
a) 212.0
32.0
b) 314.0
24.0
c) 567.0
98.0
d) None of the mentioned
4. The default value for a parameter is defined in function ………..
31
5. Python names the top level segment as…………..
6. Variable declared inside functions may have global scope (True/False)
7. Which arguments given below are skipped from function
call? a)Positional b)Default c)Keyword
d)named
8. What is the order of resolving scope in Python?
a) BGEL b)LEGB c)GEBL d)LBEG
9. Complete the function body.
def f(num):
…........... print (f(8))
a) return 0 b)print(num) c)print(“num”) d)return num
10. The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z
11. The function seed is a function which is present in the......................................... module
12. What are the outcomes of the functions shown below?
sum(2,4,6)
sum([1,2,3])
13. What is the output of the functions shown below?
min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d) 0
14. What is the output of the program given below?
a = 100
def func (a) :
a = 20
func (a)
print (' a is now ', a)
A. a is now 50 B. a is now 100 C. a is now 2 D. error
15. What will be the output of the following python code:
def A_func (x=10, y=20):
x =x+1 y=y-
2 return
(x+y)
print(A_func(5), A_func())
a)24,29 b) 15,20 c) 20,30 d) 25,30
16. Consider the following code and choose correct
answer:
def nameage(name=”kishan”, age=20):
return age, name
t=nameage(20,”kishan”)
print(t[1])
a)Kishan b) 20 c) (kishan, 20) d) (20,kishan)
32
QUESTIONS (2 MARKS)
QUESTIONS (5 MARKS)
What are the arguments supported by python? Explain each of them with a suitable example.
What is the difference between the formal parameters and actual parameters? What are their
alternative names? Also, give a suitable Python code to illustrate both.
ANSWERS
I Answer the following 1 mark
1 A
2 C
3 A
4 Header
5 _main_
6 False
7 B
8 B
9 B
10 C
11 Random
12 The first function will result in an error because the function sum() is used to find the
sum of iterable numbers. Hence the outcomes will be Error and 6respectively.
13 The function max() is being used to find themaximum value from among -3, -4 and
false. Since false amounts to the value zero, hence we are left with min(0, 2, 7) Hence
the output is 0 (false)
14 B
15 A
33
16 B
The floor of negative fractional numbers is The ceil of negative fractional numbers are
represented using the floor function represented using ceil function.
It returns the value which is just less than or It returns the value which is just greater
equal to the given value. than equal to the given value.
Default Arguments: Assign a default value to a certain parameter, it is used when the user knows
the value of the parameter, default values are specified in the function header. It is optional in the
function call statement. If not provided in the function call statement then the default value is
considered. Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with assigned values being
passed in the function call statement, the user can combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments as required in the
program. Variable-length arguments are defined with the * symbol.
2. Actual Parameter is a parameter, which is used in function call statement to send the value from
calling function to the called function. It is also known as Argument.
Formal Parameter is a parameter, which is used in function header of the called function to
receive the value from actual parameter. It is also known as Parameter. For example,
def addEm(x, y, z):
print(x + y + z)
In the above code, actual parameters are 6, 16 and 26; and formal parameters are x, y and z.
34
EXCEPTION HANDLING
Introduction to Exception Handling
Exception handling is a crucial aspect of programming, aimed at gracefully managing and recovering from
unexpected errors that can occur during program execution. Errors can range from simple typos to more
complex issues like division by zero or attempting to access a nonexistent file. Python provides a robust
mechanism for handling exceptions to prevent program crashes and improve code reliability.
Handling Exceptions Using Try-Except Blocks
The fundamental construct for handling exceptions in Python is the `try-except` block. It allows you to
define a section of code (the "try" block) where you anticipate exceptions might occur. If an exception
occurs within the "try" block, Python immediately jumps to the associated "except" block, where you can
define how to handle the exception.
Here's the syntax for a basic `try-except` block:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
- `try`: This block contains the code that might raise an exception.
- `except ExceptionType`: If an exception of the specified type occurs in the "try" block, the
code within the "except" block will execute to handle the exception.
Example 1: Handling Division by Zero try:
numerator = 10
denominator = 0
result = numerator / denominator # This may raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero.") Example
2: Handling File Not Found try:
file = open("non_existent_file.txt", "r") # This may raise a FileNotFoundError except
FileNotFoundError:
print("Error: File not found.")
The `finally` Block
In addition to `try` and `except`, you can include a `finally` block. Code within the `finally` block
always executes, regardless of whether an exception was raised or not. It is commonly used to
perform cleanup operations, such as closing files or network connections.
try:
# Code that may raise exceptions
except ExceptionType:
# Handle the exception
finally:
# Code that always executes
Example: Using `finally` try:
file = open("sample.txt", "r") content
= file.read()
except FileNotFoundError:
print("Error: File not found.") finally:
file.close() # Close the file, even if an exception occurred or not.