0% found this document useful (0 votes)
9 views

XII-CS_Function

The document outlines the syllabus for Class XII Computer Science for the academic session 2022-23, detailing the distribution of marks across various units and topics. It includes a month-wise breakdown of topics such as Computational Thinking, Programming, Data Management, and Computer Networks, along with guidelines for practical work and assessments. Additionally, it covers essential programming concepts in Python, database management, and string manipulation techniques.
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)
9 views

XII-CS_Function

The document outlines the syllabus for Class XII Computer Science for the academic session 2022-23, detailing the distribution of marks across various units and topics. It includes a month-wise breakdown of topics such as Computational Thinking, Programming, Data Management, and Computer Networks, along with guidelines for practical work and assessments. Additionally, it covers essential programming concepts in Python, database management, and string manipulation techniques.
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/ 40

KENDRIYA VIDYALAYA SANGATHAN, AHMEDABAD REGION

TERM WISE SPLIT-UP SYLLABUS


SUB: COMPUTER SCIENCE (083)
CLASS - XII (NEW SYLLABUS)
(SESSION 2022 - 23)
DISTRIBUTION OF MARKS
UNIT UNIT NAME THEORY PERIODS
MARKS THEORY PRACTICAL
1 Computational Thinking and 40 70 50
Programming -2
2 Computer Network 10 15 --
3 Data Management 20 25 20
TOTAL 70 110 70

MONTH- WISE DISTRIBUTION


Month Topics to be covered Th. Pr.
25 20
Unit I: 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
April

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)

• Introduction to files, types of files (Text file, Binary file, CSV file), relative and 10 5
May-
June

absolute paths

• Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a 20 15
textfile, 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

July

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
csv.writerow() and read from a csv file using csv.reader( )

• Data Structure: Stack, operations on stack (push & pop), implementation of stack using 15 10
August

list.
Septe
mber

• Test (Syllabus covered above)


Unit III: Database Management 10 10
• 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,update

• select, operators (mathematical, relational and logical), aliasing, distinct clause, where 15 10
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
October

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 fetchone(), fetchall(),
rowcount, creating database connectivity applications

• Evolution of networking: introduction to computer networks, evolution ofnetworking 15 0


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

• 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,
wireless/mobile communication protocol such as GSM, GPRS and WLL
• Mobile telecommunication technologies: 1G, 2G, 3G, 4G and 5G
Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible
Markup Language (XML), domain names, URL, website, web browser,web servers, web
hosting
• Revision, Project Work
ember

Pre Board Exam


Dec

Revision and practical Exam -


February
January

CBSE BOARD EXAM 2022-23


March
GUIDELINES FOR PRACTICAL
WORK
COMPUTER SCIENCE
(083) CLASS - XII
S.No Marks Term-1 Term-2
(Total 30) (15 Marks) (15 Marks)
1 Lab Test: 8 6 2
1. Python program
2. 3 SQL Queries based on one/two table(s), 2 output 4 --- 4
questions based on SQL queries
2 Report file: 7 4 3
Minimum 15 Python programs based on Term - 1Syllabus
SQL Queries – Minimum 5 sets using one table / twotables.
Minimum 2 programs based on Python - SQLconnectivity.

3 Project (using concepts learnt in Classes 11 and 12) : 8 3 5

Coding + Viva voce

4 Viva voce 3 2 1

1. Suggested Practical List:


Python Programming
● Read a text file line by line and display each word separated by a #.
● Read a text file and display the number of vowels/consonants/uppercase/lowercase
charactersin the file.
● Remove all the lines that contain the character 'a' in a file and write it to another file.
● Create a binary file with name and roll number. Search for a given roll number and
display thename, if not found display appropriate message.
● Create a binary file with roll number, name and marks. Input a roll number and update the
marks.
● Write a random number generator that generates random numbers between 1 and 6
(simulatesa dice).
● Create a CSV file by entering user-id and password, read and search the password for
given user-id.
● Write a Python program to implement a stack using list.

Database Management
● Create a student table and insert data. Implement the following SQL commands on the
studenttable:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)

6
o GROUP BY and find the min, max, sum, count and average
o Joining of two tables.
● Similar exercise may be framed for other cases.
● Integrate SQL with Python by importing suitable module.

● Similar exercise may be framed for other cases.


● Integrate SQL with Python by importing suitable module.

7
Unit I: Computational Thinking and Programming - 2
Revision of Python topics covered in Class XI
Python tokens :
(1) keyword :
Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which
it has been defined. As Python is case sensitive, keywords must be written exactly.

(2) Identifier :
Identifiers are names used to identify a variable, function, or other entities in a
program.
The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore
sign (_). This may be followed by any combination of characters a–z, A–Z, 0–9 or
underscore (_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

Variables:
A variable in a program is uniquely identified by a name (identifier). Variable in
Python refers to an object — an item or element that is stored in the memory.

Comments:
Comments are used to add a remark or a note in the source code. Comments are not
executed by interpreter. a comment starts with # (hash sign). Everything following
the # till the end of that line is treated as a comment and the interpreter simply
ignores it while executing the statement.

Mutable and immutable data types :


Variables whose values can be changed after they are created and assigned are called
mutable. Variables whose values cannot be changed after they are created and
assigned are called immutable.

● Operators:
An operator is used to perform specific mathematical or logical operation on values.
The values that the operators work on are called operands.

8
Arithmetic operators :four basic arithmetic operations as well as modular division,
floor division and exponentiation. (+, -, *, /) and (%, //, **)

Relational operators :
Relational operator compares the values of the operands on its either side and
determines the relationship among them. ==, != , > , < , <=, , >=

Logical operators :
There are three logical operators supported by Python. These operators (and, or, not)
are to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on either side. and , or , not

Assignment operator :
Assignment operator assigns or changes the value of the variable on its left. a=1+2
Augmented assignment operators :
+= , -= , /= *= , //= %= , **=

Identity operators : is, is not :


Membership operators : in, not in

● Expressions :
An expression is defined as a combination of constants, variables, and operators. An
expression always evaluates to a value. A value or a standalone variable is also
considered as an expression but a standalone operator is not an expression.

(i) 100 (iv) 3.0 + 3.14


(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"

SUMMARY
The if statement is used for selection or decision making.
• The looping constructs while and for allow sections of code to be executed
repeatedly under some condition.
• for statement iterates over a range of values or a sequence.
• The statements within the body of for loop are executed till the range of values is
exhausted.
• The statements within the body of a while are executed over and over until the
condition of the while is false.
• If the condition of the while loop is initially false, the body is not executed even
once.
• The statements within the body of the while loop must ensure that the condition
eventually becomes false; otherwise, the loop will become an infinite loop, leading to
a logical error in the program.
• The break statement immediately exits a loop, skipping the rest of the loop’s body.
Execution continues
with the statement immediately following the body of the loop. When a continue
statement is encountered, the control jumps to the beginning of the loop for the next
iteration.
• A loop contained within another loop is called a nested loop.

● STRINGS:
9
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!"""
>>> str4 = '''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 *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
'HelloHello'

(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

10
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!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]

(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, end = '')
Hello World! #output of for loop
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:
>>> 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:


len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(),
startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(),
lstrip(), rstrip(), strip(), replace(), join(), partition(), split() :

11
12
13
14
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.

● Lists:
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 is list of first five odd integers


>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers
>>> list2 = [2,4,6,8,10]

#elements of list1 followed by list2


>>> list1 + 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']

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

Output:
Red
Green
Blue
Yellow
Black

built-in functions:
16
17
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 other 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().

18
●Tuples:
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')

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)

19
Built-in functions:

len(), tuple(), count(), index(), sorted(), min(), max(), sum()

Method Description Example


len() Returns the length or the number >>>tuple1 = (10,20,30,40,50)
ofelements of the tuple passed as >>> len(tuple1)
theargument 5

tuple() Creates an empty tuple if no argumentis >>> tuple1 = tuple()


passed >>> tuple1( )
Creates a tuple if a sequence is >>> tuple1 = tuple('aeiou')#string
passed as argument >>> tuple1
('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
count() Returns the number of times the >>>tuple1=(10,20,30,10,40,10,50)
given element appears in the tuple >>> tuple1.count(10)
3
>>> tuple1.count(90)
0
index() Returns the index of the first >>> tuple1 = (10,20,30,40,50)
occurrence of the element in the >>> tuple1.index(30)
given tuple 2
>>> tuple1.index(90)
ValueError: tuple.index(x): x not
in tuple
sorted() Takes elements in the tuple and >>>tuple1=("Rama","Heena","Raj",
returns a new sorted list. It should "Mohsin","Aditya")
be noted that, sorted() does not make >>> sorted(tuple1)
any change to the original tuple ['Aditya', 'Heena', 'Mohsin', 'Raj',
'Rama']
min() Returns minimum or smallest >>>tuple1 = (19,12,56,18,9,87,34)
element of the tuple >>> min(tuple1)
max() Returns maximum or largest element 9
of the tuple >>> max(tuple1)
sum() Returns sum of the elements of the 87
tuple >>> sum(tuple1)
235

● Dictionary:
Introduction :
The data type dictionary fall 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.
20
#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'] 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}
#Marks of Suhel changed 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
21
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

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 number >>> dict1 = {'Mohan':95,'Ram':89,
of key: value pairs of the 'Suhel':92, 'Sangeeta':85}
dictionary passed as the >>> len(dict1)
argument 4
dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),
sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
[('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,
the dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])

values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89,


the dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key – >>> dict1 = {'Mohan':95, 'Ram':89,
value) pair 'Suhel':92, 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram',
89), ('Suhel', 92), ('Sangeeta', 85)])
22
get() Returns the value >>> dict1 = {'Mohan':95, 'Ram':89,
corresponding to the key 'Suhel':92, 'Sangeeta':85}
passed as the argument >>> dict1.get('Sangeeta')
If the key is not present in the 85
dictionary it will return None >>> dict1.get('Sohan')
update() appends the key-value pair of >>> dict1 = {'Mohan':95, 'Ram':89,
the dictionary passed as the 'Suhel':92, 'Sangeeta':85}
argument to the key-value >>> dict2 = {'Sohan':79,'Geeta':89}
pair of the given dictionary >>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Sohan': 79, 'Geeta':89}
>>> dict2{'Sohan': 79, 'Geeta': 89}
del() Deletes the item with the >>> dict1 = {'Mohan':95,'Ram':89,
given key To delete the 'Suhel':92, 'Sangeeta':85}
dictionary from the memory >>> del dict1['Ram']
we write: >>> dict1
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1NameError: name 'dict1' is not defined
clear() Deletes or clear all the items >>> dict1 = {'Mohan':95,'Ram':89,
of the dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{}

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().
• Dictionary is a mapping (non-scalar) data type. It is an unordered collection of key-
value pair; keyvalue pair are 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.

MARKS QUESTIONS
23
1. Which of the following is valid arithmetic operator in Python: 1
(i) // (ii) ? (iii) <(iv) and
2. Write the type of tokens from the following: 1
(i) if (ii) roll_no
3. Name the Python Library modules which need to be imported to invoke 1
the following functions:
(i) sin( ) (ii) randint ( )
4 What do you understand by the term Iteration? 1
5 Which is the correct form of declaration of dictionary? 1
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
6 Identify the valid declaration of L: 1
L = [1, 23, ‘hi’, 6].
(i) list (ii) dictionary (iii) array (iv) tuple
7 Find and write the output of the following python code: 1
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
8 Find and write the output of the following python code: 1
a=10
def call():
global a
a=15
b=20
print(a)
call()
9 Find the valid identifier from the following 1
a) My-Name b) True c) 2ndName d) S_name
10 Given the lists L=[1,3,6,82,5,7,11,92] , 1
What will be the output of print(L[2:5])
11 Write the full form of IDLE. 1
12 Identify the valid logical operator in Python from the following. 1
a) ? b) < c) ** d) and
13 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80), 1
which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))

24
14 Write a statement in Python to declare a dictionary whose keys are 1
1,2,3 and values are Apple, Mango and Banana respectively.
15 A tuple is declared as T = (2,5,6,9,8) 1
What will be the value of sum(T)?
16 Name the built-in mathematical function / method that is used to 1
return square root of a number.
17 If the following code is executed, what will be the output of the 1
following code? str="KendriyaVidyalayaSangathan"
print(str[8:16])
18 Which of the following are valid operators in Python: (i) 1
** (ii) between (iii) like (iv) ||
19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of 1
print(L[3:4])
20 What will be the output of: print(10>20) 1

2 MARKS QUESTIONS
1. Rewrite the following code in python after removing all syntax error(s). 2
Underline each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
2. Find and write the output of the following python code: 2
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)

fun('school2@com')
3. What possible outputs(s) are expected to be displayed on screen at the 2
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+1):
print (AR[K],end=”# “)

(i) 10#40#70# (ii) 30#40#50#

25
(iii) 50#60#70# (iv) 40#50#70#
4 What do you understand by local and global scope of variables? How can 2
you access a global variable inside the function, if function has a variable
with same name.
5 Evaluate the following expressions: 2

a) 8 * 3 + 2**3 // 9 – 4

b) 12 > 15 and 8 > 12 or not 19 > 4

6 Differentiate between call by value and call by reference with a suitable 2


example for each.

7 Rewrite the following code in Python after removing all syntax error(s). 2
Underline each correction done in the code.

p=30
for c in range(0,p)
If c%4==0:
print (c*4)
Elseif c%5==0:
print (c+3)
else
print(c+10)
8 What possible outputs(s) are expected to be displayed on screen at the 2
time of execution of the program from the following code? Also specify the
maximum values that can be assigned to each of the variables Lower and
Upper.
import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,4)
Upper =random.randint(2,5)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)

(i) 40# (ii) 40#50#60# (iii) 50# (iv) All of these

9 Evaluate the following expression. 2


a) 51+4-3**3//19-3
b) 17<19 or 30>18 and not 19==0

10 What do you mean by keyword argument in python? Describe with 2


example.
11 Rewrite the following code in python after removing all syntax errors. 2
Underline each correction done in the code:
def func(a):
for i in (0,a):
if i%2 =0:
s=s+1

26
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
12 What possible outputs(s) are expected to be displayed on screen at the 2
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
(i ) (ii) are correct answers.
13 What is Constraint ? Give example of any two constraints. 2
14 Predict the output of the following code. 2
def swap(P ,Q):
P,Q=Q,P
print( P,"#",Q)
return (P)
R=100
S=200
R=swap(R,S)
print(R,"#",S)
15 Evaluate the following expressions: 2
a) 6 * 3 + 4**2 // 5 – 8
b) 10 > 5 and 7 > 12 or not 18 > 3
16 Differentiate between actual parameter(s) and a formal parameter(s) with
a suitable example for each.
17 Explain the use of global key word used in a function with the help of a
suitable example.
18 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code.
Value=30
for val in range(0,Value)
If val%4==0:
27
print (val*4)
Elseif val%5==0:
print (val+3)
Else
print(val+10)
19 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 Lower and
Upper.

import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,3)
Upper =random.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)

(i) 10#40#70# (ii) 30#40#50#


(iii) 50#60#70# (iv) 40#50#70#
20 def simple_interest(p, r, t):
return (p*r*t)/100
print (simple_interest(100,5,2))

Identify the formal and actual parameters in the above code snippet.
Define formal and actual parameters in a function.

21 c = 10
def add():
global c
c=c+2
print("Inside add():", c)

add()
c=15
print("In main:", c)

output:
Inside add() : 12
In main: 15

Consider the above program and justify the output. What is the output if
“global c “ is not written in the function add().

22 Consider the following function headers. Identify the correct statement and
state reason
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):

23 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 AND minimum values that can be assigned to the variable Num
when P = 7
28
import random as r
val = 35
P=7
Num = 0
for i in range(1, 5):
Num = val + r.randint(0, P - 1)
print(Num, " $ ", end = "")
P=P–1

(a) 41 $ 38 $ 38 $ 37 $
(b) 38 $ 40 $ 37 $ 34 $
(c) 36 $ 35 $ 42 $ 37 $
(d) 40 $ 37 $ 39 $ 35 $

24 Find the output of the following program;


def increment(n):
n.append([4])
return n
l=[1,2,3]
m=increment(l)
print(l,m)

25 Evaluate the following:


a. 45<89 and 7>12 or not 18>3
b. 6*3+2**4//5-2

3 MARKS QUESTIONS
1. Find and write the output of the following python code: 3
def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)

R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
2. Write a program in Python, which accepts a list Lst of numbers and n is a
numeric value by which all elements of the list are shifted to left.

Sample Input Data of the list :

Lst= [ 10,20,30,40,12,11], n=2

Output Lst = [30,40,12,11,10,20]

3. Write a program in Python, which accepts a list Arr of numbers , the


function will replace the even number by value 10 and multiply odd
number by 5 .
Sample Input Data of the list is:

29
arr=[10,20,23,45]
output : [10, 10, 115, 225]

4 Write a program in Python, which accepts a list Arr of numbers and n is a


numeric value by which all elements of the list are shifted to left.

Sample Input Data of the list :


Arr= [ 10,20,30,40,12,11], n=2
Output :
Arr = [30,40,12,11,10,20]

5 Write a program to reverse elements in a list where arguments are start and 3
end index of the list part which is to be reversed. Assume that start<end,
start>=0 and end<len(list)
Sample Input Data of List :
my_list=[1,2,3,4,5,6,7,8,9,10]
Output is
my_list=[1,2,3,7,6,5,4,8,9,10]

6 Write program to add those values in the list of NUMBERS, which are odd. 3
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16

7 Write a program to replaces elements having even values with its half and 3
elements having odd values with twice its value in a list.
eg: if the list contains
3, 4, 5, 16, 9
then rearranged list as
6, 2,10,8, 18

8 Write a Python program to find the maximum and minimum elements in the 3
list entered by the user.

9 Write a program in python to print b power p. 3

10 Write a program to print of fibonnaci series upto n. 3

for example if n is 50 then output will be :


0
1
1
2
3
5
8
13
21
34

30
MARKING SCHEME
1 MARKS QUESTIONS
1. Which of the following is valid arithmetic operator in Python: 1
(i) // (ii) ? (iii) <(iv) and
Answer (i) //
2. Write the type of tokens from the following: 1
(i) if (ii) roll_no
Answer (i) Key word (ii) Identifier
(1/2 mark for each correct type)
3. Name the Python Library modules which need to be imported to 1
invoke the
following functions:
(i) sin( ) (ii) randint ( )
Answer (i) math (ii) random
(1/2 mark for each module)
4 What do you understand by the term Iteration? 1
Answer Repeatation of statement/s finite number of times is known as
Iteration.
(1 mark for correct answer)
5 Which is the correct form of declaration of dictionary? 1
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Answer (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
6 Identify the valid declaration of L: 1
L = [1, 23, ‘hi’, 6].
(i) list (ii) dictionary (iii) array (iv) tuple
Answer (i) List
7 Find and write the output of the following python code: 1
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
Answer aaaaaa----- OR infinite loop
8 Find and write the output of the following python code: 1
a=10
def call():
global a
a=15
b=20
print(a)
call()
Answer 15
9 Find the valid identifier from the following 1

a) My-Name b) True c) 2ndName d) S_name

Answer s) S_name

10 Given the lists L=[1,3,6,82,5,7,11,92] , 1

31
What will be the output of
print(L[2:5])
Answer [6,82,5]

11 Write the full form of IDLE. 1

Answer Integrated Development Learning Environment

12 Identify the valid logical operator in Python from the following. 1

a) ? b) < c) ** d) and

Answer d) and

13 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80), 1


which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))
Answer b) Tup[2]=90

14 Write a statement in Python to declare a dictionary whose keys are 1


1,2,3 and values are Apple, Mango and Banana respectively.

Answer Dict={1:’Apple’, 2: ’Mango’,3 : ‘Banana’}

15 A tuple is declared as T = (2,5,6,9,8) 1


What will be the value of sum(T)?
Answer 30

16 Name the built-in mathematical function / method that is used to 1


return square root of a number.

Answer sqrt()

17 If the following code is executed, what will be the output of the 1


following code? str="KendriyaVidyalayaSangathan"

print(str[8:16])

Answer Vidyalay

18 Which of the following are valid operators in Python: 1

(i) ** (ii) between (iii) like (iv) ||

Answer a) (I) and (iv)

19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of 1
print(L[3:4])
32
Answer [“N”]
20 What will be the output of: 1
print(10>20)
Answer False
2 MARKS QUESTIONS
1. Rewrite the following code in python after removing all syntax 2
error(s). Underline each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
Answer To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)
(1/2 mark for each correction)
2. Find and write the output of the following python code: 2
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
Answer SCHOOLbbbbCOM
(2 marks for correct output)
Note: Partial marking can also be given
3. What possible outputs(s) are expected to be displayed on screen at 2
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+1):
print (AR[K],end=”# “)

(i) 10#40#70# (ii) 30#40#50#


(iii) 50#60#70# (iv) 40#50#70#
Answer (ii) 30#40#50# Maximum value FROM,TO is 3,4
(1/2 mark each for maximum value)
(1 mark for correct option)
33
4 What do you understand by local and global scope of variables? How 2
can you access a global variable inside the function, if function has
a variable with same name.
Answer A global variable is a variable that is accessible globally. A local
variable is one that is only accessible to the current scope, such as
temporary variables used in a single function definition.
A variable declared outside of the function or in global scope is
known as global variable.
This means, global variable can be accessed inside or outside of the
function where as local variable can be used only inside of the
function. We can access by declaring
variable as global A.
5 Evaluate the following expressions: 2
a) 8 * 3 + 2**3 // 9 – 4
b) 12 > 15 and 8 > 12 or not 19 > 4
Answer a) 25
b) False
6 Differentiate between call by value and call by reference with a 2
suitable example for each.
Answer In the event that you pass arguments like whole numbers, strings
or tuples to a function, the passing is like call-by-value because you
can not change the value of the immutable objects being passed to
the function. Whereas passing mutable objects can be considered as
call by reference because when their values are changed inside the
function, then it will also be reflected outside the function.
7 Rewrite the following code in Python after removing all syntax 2
error(s). Underline each correction done in the code.

p=30
for c in range(0,p)
If c%4==0:
print (c*4)
Elseif c%5==0:
print (c+3)
else
print(c+10)
Answer p=30
for c in range(0,p):
if c%4==0:
print (c*4)
elif c%5==0:
print (c+3)
else:

34
print(c+10)
8 What possible outputs(s) are expected to be displayed on screen at 2
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 Lower and Upper.

import random

AR=[20,30,40,50,60,70];

Lower =random.randint(1,4)

Upper =random.randint(2,5)

for K in range(Lower, Upper +1):

print (AR[K],end=”#“)

(i) 40# (ii) 40#50#60# (iii) 50# (iv) All of these

Answer (iv) All of these

9 Evaluate the following expression. 2


a) 51+4-3**3//19-3
b) 17<19 or 30>18 and not 19==0

Answer 51
True
10 What do you mean by keyword argument in python? Describe 2
with example.
Answer When you assign a value to the parameter (such as param=value)
and pass to the function (like fn(param=value)), then it turns into
a keyword argument.
11 Rewrite the following code in python after removing all 2
syntax errors. Underline each correction done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)

35
Answer def func(a): #def
s=m=n=0 #local variable
for i in (0,a): #indentation and frange function missing
if i%2==0:
s=s+I
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15) 2 marks for any four corrections.
12 What possible outputs(s) are expected to be displayed on screen 2
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
Answer (i ) (ii) are correct answers.
13 What is Constraint ? Give example of any two constraints. 2
Answer Constraints are the checking condition which we apply on table to
ensure the correctness of data . example primary key, nut null,
default, unique etc
14 Predict the output of the following code. 2
def swap(P ,Q):
P,Q=Q,P
print( P,"#",Q)
return (P)
R=100
S=200
R=swap(R,S)

36
print(R,"#",S)
Answer 200 # 100

200 # 200
15 Evaluate the following expressions: 2
a) 6 * 3 + 4**2 // 5 – 8
b) 10 > 5 and 7 > 12 or not 18 > 3
Answer a) 13
b) False
16 Differentiate between actual parameter(s) and a formal
parameter(s) with a suitable example for each.
Answer The list of identifiers used in a function call is called actual
parameter(s) whereas the list of parameters used in the function
definition is called formal parameter(s).
Actual parameter may be value / variable or expression.
Formal parameter is an identifier.
Example:
def area(side):
# line 1
return side*side;
print(area(5))
# line 2
In line 1, side is the formal parameter and in line 2, while invoking
area() function, the value 5 is the actual parameter.
formal parameter, i.e. a parameter, is in the function
definition. An actual parameter, i.e. an argument, is in a
function call.
17 Explain the use of global key word used in a function with the help
of a suitable example.
Answer Use of global key word:
In Python, global keyword allows the programmer to modify the
variable outside the current scope. It is used to create a global
variable and make changes to the variable in local context. A variable
declared inside a function is by default local and a variable declared
outside the function is global by default. The keyword global is
written inside the function to use its global value. Outside the
function, global keyword has no effect. Example
c = 10 # global variable
def add():
global c
c = c + 2 # global value of c is incremented by 2
print("Inside add():", c)

add()
c=15
print("In main:", c)

37
output:
Inside add() : 12
In main: 15

18 Rewrite the following code in Python after removing all syntax


error(s).
Underline each correction done in the code.
Value=30
for val in range(0,Value)
If val%4==0:
print (val*4)
Elseif val%5==0:
print (val+3)
Else
print(val+10)
Answer Value=30
for VAL in range(0,Value) :
if val%4==0:
print (VAL*4)
elif val%5==0:
print (VAL+3)
else:
print(VAL+10
19 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 Lower and Upper.

import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,3)
Upper =random.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)

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

Answer OUTPUT: (ii)


Maximum value of Lower: 3
Maximum value of Upper: 4
20 def simple_interest(p, r, t):
return (p*r*t)/100
print (simple_interest(100,5,2))

38
Identify the formal and actual parameters in the above code
snippet. Define formal and actual parameters in a function.
OR

Answer Answer: p,r,t is formal parameters and 100,5,2 are actual


parameters

21 c = 10
def add():
global c
c=c+2
print("Inside add():", c)

add()
c=15
print("In main:", c)

output:
Inside add() : 12
In main: 15
Consider the above program and justify the output. What is the
output if “global c “ is not written in the function add().

Answer Answer : In the function add() global c is increment due to use of


global keyword. In the main program local c is printed as local takes
precedence over global c.
If global c is not used then c=c+2 will show error as there is no
local variable c in function.
22 Consider the following function headers. Identify the correct
statement and state reason
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Answer 3) def correct(a=1,b=2,c=3):
Constant parameter can be used from right hand side.
23 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 AND minimum values that can be assigned
to the variable Num when P = 7

import random as r
val = 35
P=7
Num = 0
for i in range(1, 5):
Num = val + r.randint(0, P - 1)
print(Num, " $ ", end = "")
P=P-1
(a) 41 $ 38 $ 38 $ 37 $ (b) 38 $ 40 $ 37 $ 34 $
(c) 36 $ 35 $ 42 $ 37 $ (d) 40 $ 37 $ 39 $ 35 $

Answer (a) 41 $ 38 $ 38 $ 37 $
39
(d) 40 $ 37 $ 39 $ 35 $
Maximum value of Num when P = 7 : 42
Minimum value of Num when P = 7 : 35
24 Find the output of the following program;
def increment(n):
n.append([4])
return n
l=[1,2,3]
m=increment(l)
print(l,m)
Answer [1, 2, 3, [4]] [1, 2, 3, [4]]

25 Evaluate the following:


a. 45<89 and 7>12 or not 18>3
b. 6*3+2**4//5-2

Answer a. False
b. 19

3 MARKS QUESTIONS
1. Find and write the output of the following python code: 3
def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)

R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
Answer 250 # 150
250 # 100
130 # 100

(1 mark each for correct line)


2. Write a program in Python, which accepts a list Lst of
numbers and n is a numeric value by which all elements
of the list are shifted to left.

Sample Input Data of the list

Lst= [ 10,20,30,40,12,11], n=2

Output Lst = [30,40,12,11,10,20]

Answer L=len(Lst)
for x in range(0,n):
y=Lst[0]
for i in range(0,L-1):
40
Lst[i]=Lst[i+1]
Lst[L-1]=y
print(Lst)
#Note : Using of any correct code giving the same result
is also accepted.

3. Write a program in Python, which accepts a list Arr of


numbers , the function will replace the even number
by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:

arr=[10,20,23,45]
output : [10, 10, 115, 225]
Answer l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
print(arr)

1 mark for function


1 mark for loop and condition checking
1 mark for if and else
4 Write a program in Python, which accepts a list Arr of
numbers and n is a numeric value by which all elements
of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
Answer Arr= [ 10,20,30,40,12,11], n=2

L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
5 Write a program to reverse elements in a list where 3
arguments are start and end index of the list part which is
to be reversed. Assume that start<end, start>=0 and
end<len(list)
Sample Input Data of List
my_list=[1,2,3,4,5,6,7,8,9,10]
Output is
my_list=[1,2,3,7,6,5,4,8,9,10]
41
Answer my_mylist=[1,2,3,4,5,6,7,8,9,10]

l1=mylist[:start:1] ½ Mark
l2=mylist[end:start-1:-1] ½ Mark
l3=mylist[end+1:] ½ Mark
final_list=l1+l2+l3 ½ Mark
print (final_list) ½ Mark
Or any other relevant code
6 Write program to add those values in the list of 3
NUMBERS, which are odd.
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16
Answer NUMBERS=[20,40,10,5,12,11]
s=0
for i in NUMBERS:
if i%2 !=0:
s=s+i
print(s)
7 Write a program to replaces elements having even values 3
with its half and elements having odd values with twice its
value in a list.

eg: if the list contains


3, 4, 5, 16, 9
then rearranged list as
6, 2,10,8, 18
Answer L=[3, 4, 5, 16, 9]

for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
8 Write a Python program to find the maximum and minimum 3
elements in the list entered by the user.
Answer lst = []
num = int(input(“How many numbers”))

for n in range (nm):


numbers = int(input”Enter number :”))
lst.append(numbers)

print(“Maximum element in the list is :”,max(lst))


print(“Minimum element in the list is :”,min(lst))
9 Write a program in python to print b power p. 3
Answer b=int(input("Enter base number"))
p=int(input("Enter exp no."))

t=b
42
for i in range(p-1):
t=t*b
print(t)
10 Write a program to print of fibonnaci series upto n. 3

for example if n is 50 then output will be :


0
1
1
2
3
5
8
13
21
34
Answer n=int(input("Enter any nubmer"))
a=0
b=0
c=1
while a<=n:
print(a)
b=c
c=a
a=b+c

FUNCTIONS
Notes

• The act of partitioning a program into individual components is called "Modularity".


• A module is a separately saved unit whose functionality can be reused.
• A Python module has the .py extension.
• A Python module can contain objects like docstrings, variables, constants, classes,
objects, statements, functions etc.
• The Python modules that come preloaded with Python are called "standard library
modules".
• A function is a named block of statements that can be invoked by its name.
• Python can have three types of functions i.e., built-in functions, functions in
modules and user-defined functions
• The docstrings are useful for documentation purpose.
• Python module can be imported in a program using import statement.
• There are two forms of import statements:
(i) import <module name>
(ii) from <module name> import <object>
• The built-in functions of Python are always available, one needs not import any
module for them.
• The math module of Python provides mathematical functionality.
• sys.stdin is the most widely used method to read input from the command line or
terminal.
• The command line sys.argv arguments is another way that we can grab input, and
environment be used from within our programs.
• The basic I/O (Input/Output) functions are input() and print() respectively.
43

You might also like