XII-CS_Function
XII-CS_Function
• 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
• 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
• 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
4 Viva voce 3 2 1
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.
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.
● 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 :
+= , -= , /= *= , //= %= , **=
● 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.
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 +.
(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]
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 +.
15
Repetition
Python allows us to replicate a list using repetition
operator depicted by symbol *.
Membership
Like strings, the membership operators in checks if the element is present in the list
and returns True, else returns False.
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
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.
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:
● 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}
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();
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=”# “)
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
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=”#“)
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=”#“)
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):
(a) 41 $ 38 $ 38 $ 37 $
(b) 38 $ 40 $ 37 $ 34 $
(c) 36 $ 35 $ 42 $ 37 $
(d) 40 $ 37 $ 39 $ 35 $
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.
29
arr=[10,20,23,45]
output : [10, 10, 115, 225]
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.
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
Answer s) S_name
31
What will be the output of
print(L[2:5])
Answer [6,82,5]
a) ? b) < c) ** d) and
Answer d) and
Answer sqrt()
print(str[8:16])
Answer Vidyalay
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=”# “)
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)
print (AR[K],end=”#“)
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
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#
38
Identify the formal and actual parameters in the above code
snippet. Define formal and actual parameters in a function.
OR
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().
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]]
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
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.
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)
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.
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”))
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
FUNCTIONS
Notes