KEMBAR78
Abps, Awarpur Class Xii - Study Material 2025-26 | PDF | Computer Network | Data Type
0% found this document useful (0 votes)
24 views36 pages

Abps, Awarpur Class Xii - Study Material 2025-26

The document outlines the Class XII Computer Science syllabus for the academic year 2025-26, covering key topics such as computational thinking, programming in Python, computer networks, and database management. It includes detailed descriptions of Python programming concepts, data types, and operations, as well as networking fundamentals and SQL database interactions. The material serves as a comprehensive guide for students to prepare for their studies in computer science.

Uploaded by

komalnibrad71
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)
24 views36 pages

Abps, Awarpur Class Xii - Study Material 2025-26

The document outlines the Class XII Computer Science syllabus for the academic year 2025-26, covering key topics such as computational thinking, programming in Python, computer networks, and database management. It includes detailed descriptions of Python programming concepts, data types, and operations, as well as networking fundamentals and SQL database interactions. The material serves as a comprehensive guide for students to prepare for their studies in computer science.

Uploaded by

komalnibrad71
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

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)

● Data communication terminologies: concept of communication, components of data communication


(sender,receiver, message, communication media, protocols), measuring capacity of communication
media (bandwidth, data transfer rate), IP address, switching techniques (Circuit switching, Packet
switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable),
Wireless media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking topologies
(Bus, Star, Tree)
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup Language
(XML), domain names, URL, website, web browser, web servers, web hosting.

Unit 3: Database Management


● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data Manipulation Language,
data type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create
database, use database, show databases, drop database, show tables, create table, describe table, alter
table (add and remove an attribute, add and remove primary key), drop table, insert, delete, select,
operators (mathematical, relational and logical), aliasing, distinct clause, where clause, in, between,
order by, meaning of null, is null, is not null, like, update command, delete command, aggregate
functions (max, min, avg, sum, count), group by, having clause, joins: cartesian product on two tables,
equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing insert, update,
delete queries using cursor, display data by using connect(), cursor(), execute(), commit(), fetchone(),
fetchall(), rowcount, creating database connectivity applications, use of %s format specifier or format()
to perform queries

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 IN PYTHON:

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.

The sequence data types are:

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.

>>> str1 = 'Hello World!'

>>> str2 = "Hello World!"

>>> str3 = """Hello World!"""

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 +.

>>> str1 = 'Hello' #First string

>>> str2 = 'World!' #Second string

>>> str1 + str2 #Concatenated strings

'HelloWorld!'

(ii) Repetition: Python allows us to repeat the given string using repetition operator, which is denoted
by symbol *.

>>> str1 = 'Hello' #assign string 'Hello' to str1

>>> str1 * 2 #repeat the value of str1 2 times

'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.

>>> str1 = 'Hello World!'

>>> 'W' in str1

True

>>> 'Wor' not in str1

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).

>>> str1 = 'Hello World!'


>>> str1[1:5] #gives substring starting from index 1 to 4
'ello'
>>> str1[7:10] #gives substring starting from 7 to 9
'orl'
>>> str1[3:20] #index that is too big is truncated down to the end of the string
'lo World!'
>>> str1[7:2] #first index > second index results in an empty '' string
(v) Traversing a string using loops: We can access each character of a string or traverse a string
using for loop and while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch)
H
e
l
l
o

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.

(B) String Traversal Using while Loop:

7
>>> str1 = 'Hello World!'

>>> index = 0 #len(): a function to get length of string

>>> while index < len(str1):

print(str1[index], end = '')

index += 1

Hello World! #output of while loop

Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.

(vi) built-in functions:


i. len() : Returns the length of the given string.
>>> str1 = 'Hello World!'
>>> len(str1)
12
ii. title(): Returns the string with first letter of every word in the string in uppercase and
rest in lowercase.
>>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
iii. lower(): Returns the string with all uppercase letters converted to lowercase
>>> str1 = 'hello WORLD!'
>>> str1.lower()
'hello world!'
iv. upper(): Returns the string with all lowercase letters converted to uppercase
>>> str1 = 'hello WORLD!'
>>> str1.upper()
'HELLO WORLD!'
v. count(str, start, end): Returns number of times substring str occurs in the given string. If
we do not give start index and end index then searching starts from index 0 and ends at
length of the string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
vi. find(str,start, end): Returns the first occurrence of index of substring str occurring in the
given string. If we do not give start and end then searching starts from index 0 and ends at
length of the string. If the substring is not present in the given string, then the function
returns -1.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
8
>>> str1.find('Hee')
-1
vii. index(str, start, end): Same as find() but raises an exception if the substring is not present in the
given string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found

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

>>> str1 = 'India is a Great Country'


>>> str1.partition('is')
('India ', 'is', ' a Great Country')
>>> str1.partition('are')
('India is a Great Country',' ',' ')

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.

• Elements of a list are put in square brackets separated by comma.


• A list within a list is called a nested list. List indexing is same as that of strings and starts at 0.
Two- way indexing allows traversing the list in the forward as well as in the backward direction.
• Operator + concatenates one list to the end of another list.
• Operator * repeats a list by specified number of times.
• Membership operator in tells if an element is present in the list or not and not in does the
opposite.
• Slicing is used to extract a part of the list.
• There are many list manipulation functions
including: len(), list(), append(), extend(), insert(), count(), find(), remove(), pop(), reverse(),
sort(), sorted(), min(), max(), sum().
C. TUPLE:
Introduction:
A tuple is an ordered sequence of elements of different data types, such as integer, float, string,
list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas. Like list and string, elements of a tuple can be accessed using index
values, starting from 0.
Indexing:
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Tuple is Immutable:

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.

>>> tuple1 = (1,3,5,7,9)


>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 #concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

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.

#dict1 is an empty Dictionary created


#curly braces are used for dictionary
>>> dict1 = {}
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

Accessing items in a dictionary using keys:


We have already seen that the items of a sequence (string, list and tuple) are accessed using a
technique called indexing. The items of a dictionary are accessed via the keys rather than via their
relative positions or indices. Each key serves as the index and maps to a value. The following
example shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']

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();

Method Description Example

len() Returns the length or >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, Sangeeta':85}


number of key: value pairs >>> len(dict1)
of the dictionary passed as 4
the argument

dict() Creates a dictionary from a pair1 =


sequence of key-value pairs [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan':95, 'Ram':89,'Suhel':92,'Sangeeta': 85}

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)])

get() Returns the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}


value corresponding to the >>> dict1.get('Sangeeta')
key passed as the argument 85
If the key is not present in >>> dict1.get('Sohan')
the dictionary it will return
None

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

clear() Deletes or clear all the >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,


items of the dictionary 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{}

• 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=”# “)

(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

4. Identify the invalid python statement from the following:


a. d = dict() b. l = {} c. f = () d. g = dict {}
5. List AL is defined as follows: AL = [1,2,3,4,5]
Which of the following statements removes the middle element 3 from it, so that list AL equals
[1,2,4,5]. (Multiple options are correct)
a. del a[2] b. a[2:3] = [] c. a[2:2] = [] d. a[2] = [] e. a.remove(3)
19
6. Select the correct output of the following string operation.
str1 = “Waha”
print(str1[:3] + “Bhyi” + str1[-3:])
a. Wah Bhyi Wah b. Wah Bhyi aha c. WahBhyiWah d. WahBhyiWaha

7. Select the correct output of the following code:


event = “G20 Presidency@2023”
L = event.split(“ “)
print(L[::-2])
a. [“G20”] b. G20 c. [“Presidency@2023”] d. “Presidency@2023”

8. What is printed when the following code is executed?


K = [“Ram”, “Shyam”, “Sita”, “Gita”]
print(K[-1][-1])
a. R b. m c. Ram d. Gita e. a
9. What will be the output of the following code?
dict = {“Jo”:1, “Ra”:2}
dict.update({“Pho”:2})
print(dict)
a. {“Jo”:1, “Ra”:2, “Pho”:2} b. {“Jo”:1, “Ra”:2}
c. {“Jo”:1, “Pho”:2} d. Error

10. What will be the output of the following Python code?


d1 = {‘a’:10, ‘b’:2, ‘c’:3}
str1 = ‘’
for i in d1:
str1 = str1 + str(d1[i]) + ‘ ‘
str2 = str1[:-1]
print(str2[::-1])
a. 3, 2 b. 3, 2, 10 c. 3, 2, 01 d. Error
ASSERTION & REASON based questions.
1. Assertion (A): List is a mutable data type of Python.
Reason (R): In place change is not possible in list elements.
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.
2. Assertion (A): in and not in are called membership operators.
Reason (R): They return True based on the presence of a character/substring in a given string
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.
3. Assertion (A): Python strings are mutable in nature.
Reason (R): Python strings are stored in memory by storing individual characters in
contiguous memory locations.
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.
20
D - A is false but R is true.
E - Both A and R are false.

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.

1. The statement is an empty statement in Python.


pass
2. A statement skips the rest of the loop and jumps over to the statement
following the loop.
break
3. Python's cannot be used as variable name.
keywords
4. The explicit conversion of an operand to a specific type is called .
type casting.
5. The data types whose values cannot be changed in place are called types.
immutable
6. The can add an element in the middle of a list.
insert()
7. The only adds an element at the end of a list.
append()
8. The keys of a dictionary must be of type.
immutable
9. Dictionary is an set of elements.
unordered
10. To get all the keys of a dictionary, method is used.
keys()

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.

Structure of functions in Python

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

A function in Python is defined as given below:

def< function name >(parameters):

[“ ” ”<function’s docstring>” “ “]

<statements> [<statements>]

……………………..

 Keyword def that marks the start of the function header.

 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.

 A colon (:) to mark the end of the function header.

 Optional documentation string (docstring) to describe what the function does.

 One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).

 An optional return statement to return a value from the function.

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():

print('Hello I am learning how to create function in python.')

def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))

# main program

# calling the function message()


message()

# calling the function sum()

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.

Parameters and Arguments

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:-

def interest(prin, time, rate):

return prin * time * rate

print (interest ( prin = 2000 , time = 2 , rate 0.10 ))

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:-

def interest(prin, cc, ime=2, rate=0.09):

return prin * time * rate

Types of user defined function


1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def Add():
a= int (input(“Enter First Number”)) b=
int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)

2. With Argument No return


def Add(a,b):
c=a+b
print(“The Sum of inputted Numbers is:”, C)

num1= int (input(“Enter First Number”))


num2= int (input(“Enter Second Number”))
Add(num1,num2)

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.

3. No Argument with return


def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
26
x= add()
print (“The Sum of inputted Numbers is:”, x)

Note: As return does not show the result we have to store the returned value on another
variable x.

4. With Argument with return


def Add (a,b):
c=a+b return c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)

Calling function and Called function:


 Function which is called by another Function is called Called Function. The called function
contains the definition of the function and formal parameters are associated with them.
 The Function which calls another Function is called Calling Function and actual Parameters
are associated with them.
 In python, a function must be defined before the function call otherwise python interpreter gives
an error.
Difference between Arguments and parameters
These two terms are very interchangeable, so it is not so important to know the difference. The terms
they refer to are almost identical. However, in order to sound more professional, correct terminology is
important.
Function Parameters: Variables that are in brackets when defining the function. When a method is
called, the arguments are the data passed to the method’s parameters.
Function arguments: Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of arguments
you put in a function call. The number of arguments must be exactly the same as the number of
parameters.
In the example below, the variable name is the input parameter, whereas the value, “Arnav”, passed in
the function call is the argument.

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

randint() – function takes starting and ending values both

randrange()-function takes only starting value and ending-1

value

random()-generates decimal values between 0 and 1 but not include 1

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 = "-")

(i) 30-40-50- (ii) 10-20-30-40- (iii) 30-40-50-60- (iv) 30-40-50-60-70-

OUTPUT – (i) 30-40-50- Minimum value of BEGIN: 1 Minimum value of LAST: 2

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.

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):
print (AR[K],end=”#“)
(i)10#40#70# (ii)30#40#50# iii)50#60#70# (iv)40#50#70#

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=’@’)

(a) 30 @ (b) 10@20@30@40@50@ (c) 20@30 (d) 40@30@


Ans
(a) & (b)
Maximum value of BEG: 2
Maximum value of END: 4

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#

Ans: (ii) 30#40#50#

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

Ans: (i) (ii) are correct answers.

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)

Write the output of the pseudo code:


def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
QUESTIONS (3 MARKS)

Differentiate ceil() and floor() function?

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

II Answer the following 2 marks


2
4
III Answer the following 3 marks
Floor Function Ceil Function
floor function returns the integer value just ceil function returns the integer value
lesser than the given rational value. greater than the given rational value

represented as floor(x). represented as ceil(x)

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.

ANSWER THE FOLLOWING (5 MARKS)

1 Python supports four argument types:

Positional Arguments: Arguments passed to a function in correct positional order, no. of


arguments must match with no. of parameters required.

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)

addEm (6, 16, 26)

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.

Multiple Choice Questions (MCQ)


35
1. Which of the following is the primary purpose of exception handling in programming?
- A. To intentionally crash the program B. To ignore errors and continue program execution
- C. To gracefully manage and recover from unexpected errors
- D. To create errors for testing purposes
Answer: C
2. What is the primary role of the `try` block in a try-except construct?
- A. To execute code that may raise an exception B. To handle exceptions
- C. To indicate the end of the try-except construct
- D. To prevent exceptions from occurring
Answer: A
3. In a try-except block, if an exception occurs, which block is executed?
- A. The try block - B. The except block
- C. Both try and except blocks simultaneous - D. None of the above
Answer: B
4. What is the purpose of the `finally` block in exception handling?
- A. To specify the types of exceptions to catch
- B. To execute code regardless of whether an exception occurred or not
- C. To create custom exceptions
- D. To prevent exceptions from propagating
Answer: B
5. Which keyword is used to specify the type of exception to catch in an except block?
- A. `catch` - B. `try` - C. `except` - D. `handle`
Answer: C
6. In a try-except block with multiple except blocks, which block will be executed if an
exception matches multiple except blocks?
- A. The first matching except block encountered from top to bottom
- B. All matching except blocks simultaneously
- C. The last matching except block encountered from top to bottom
- D. None of the above
Answer: A
7. What type of error does a `ValueError` exception typically represent in Python?
- A. A network-related error - B. A division by zero error
- C. An error related to invalid data conversion. - D. A file handling error
Answer: C
8. Which exception is raised when attempting to access a non-existent file?
- A. FileNotFoundError - B. FileNotAccessibleError
- C. NonExistentFileError - D. InvalidFileAccessError
Answer: A
9. What is the main purpose of using a `try-except-finally` construct?
- A. To create custom exceptions - B. To ensure that no exceptions are raised
- C. To gracefully manage exceptions and execute cleanup code
- D. To replace if-else statements
Answer: C
10. What happens if an exception is raised in the `finally` block?
- A. The program crashes B. The exception is caught and handled by the `except` block
- C. The program continues executing normally
- D. The `finally` block cannot raise exceptions
Answer: A
**END***
36

You might also like