XII - CS - Bridge Course
XII - CS - Bridge Course
FOR
CLASS XII
SESSION : 2024-25
Bridge Course XII – Computer Science Page 1 of 60
Bridge Course XII – Computer Science Page 2 of 60
BRIDGE COURSE FOR CLASS XII
COMPUTER SCIENCE
INSPIRATION
Smt. Sona Seth, Deputy Commissioner, KVS Regional Office Lucknow
MENTOR
Sh. Anoop Awasthi, Assistant Commissioner, KVS Regional Office Lucknow
Smt. Archana Jaiswal, Assistant Commissioner, KVS Regional Office Lucknow
Sh. Vijay Kumar, Assistant Commissioner, KVS Regional Office Lucknow
Coordinator
Sh. Samrat Kohli, Vice-Principal, KV OEF Kanpur
3 Conditional Statements 13
4 Looping Statements 16
5 Programs on Loops 20
6 String Introduction 21
8 Programs on Strings 29
9 List Introduction 30
12 Tuples 40
13 Dictionary Introduction 44
A Python program is written with the help of character set available for the language, tokens,
keywords, identifiers, operators and control statements.
Example :
‘’’ this is a
In Python programming indentation plays a key role in making the code easier to read. Indentation
uses whitespaces to indicate a block of code usually 4 spaces)
• ( optional) Lines starting with import allow you to use functionalities from pre-written code
modules.
import
•Lines that make up the core logic of your program. Statements end with a newline character.
•input()- to read any value from the user
stateme
•print()- to display the result on screen
nt
• (Optional): Lines starting with # are ignored by the interpreter but provide notes for human
readers.
•Single line comment ( using #)
comment
•Multiline comment (using ‘’’ ‘’’) (triple quotes)
Python's code is made up of smaller elements called tokens. These tokens have specific meanings
and work together to form instructions:
Keywords: Reserved words with special meanings in the language (e.g., if, else, for, while and
many more).
Identifiers: User-defined names for variables, functions, and classes. They must follow
naming conventions (start with a letter or underscore, followed by letters, numbers, or
underscores).
Operators: Symbols used to perform operations on data (e.g., +, -, *, /).
Worksheet Level - 1
(MCQ)
1. Find the error
r=7
if r>3:
print(“value is less than 3”)
2.What is Python? List some popular applications of Python in the world of technology.
3. What do you mean by comments? How will you add inline, single line or multiline comments in
Python?
6.The lines ignored by the compiler and not executed are called
a)operators b)operands c)functions d)comments
14. Evaluate:
2+3//4-7
15. Evaluate:”cs”**10%3
2. Write a Python program to print the following string in a specific format (seethe output).
Output :
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,Like a
diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
4. Which of the following are valid identifiers?a)odd even b)odd_even c)print d)odd-even
6.The lines ignored by the compiler and not executed are calleda)operators b)operands c)functions
d)comments
14. Evaluate:
2+3//4-7
15. Evaluate:
”cs”**10%3
Examples
Integer : 3,6,,67
Float : 3.5678, 23.07
Complex : 2+3j, 4-7j
String : ‘ABCD’
List: *23,34,56+
Tuple : ( 23,34,56)
Dictionary ,‘ a’:2, ‘b’:3-
Operators
Examples:
Worksheet Level - 2
1 Kumar is a newbie in Python language , he studied about mutable and immutable datatypes in
Python from the notes given above. But he is still confused on the usage of these data types,
help him understanding the concept by answering the following
a) He wants to store names of seven wonders in the world, which datataype will he use
i) List ii) string iii) tuple iv) dictionary
b) Which datatype will he use to store five classmates name and address studying with
him in his brothers tution class
i) List ii) string iii) tuple iv) dictionary
c) Which of the following will he use to keep monthly expenses of his home?
The IF Conditionals
The if conditionals of Python come in multiple forms: plain if conditional, if-else conditional
and if-elif conditional.
Plain if Conditional Statement
An if statement tests a particular condition; if condition evaluates to true, a course-of-action
is followed i.e., a statement or set-of-statements is executed. If the condition is false, it does
nothing. The syntax of if statement is as shown below:
if <conditional expression>:
<statement(s)>
For example, consider the following code fragment:
if a>b:
print(“A has more than B has”)
print(“Their difference is”, (a-b))
The if-else Conditional Statement
This form of if statement tests a condition and if the condition evaluates to true, it carries
out statements of if block and in case condition evaluates to false, it carries out statement
of else block. The syntax of the if-else statement is:
if <conditional expression>:
<statement(s)>
else:
<statement(s)>
For example, consider the following code fragments using if-else conditionals:
if a>0:
print(a, “is a positive number”)
else:
print(a, “is either negative number or zero”)
The if-elif Conditional Statement
Sometimes, you want to check a condition when control reaches else, i.e., condition test in
the form of else if. To serve such conditions, Python provides if-elif-else statement. The
general form of this statement is:
if <conditional expression>:
<statement(s)>
*elif <conditional expression>:
<statement(s)>
elif <conditional expression>:
<statement(s)>
…
else:
<statement(s)>+
Worksheet Level - 1
1)The ……………… statement forms the selection construct in Python.
A)if else B)if C)for d)For
3) An ……………… statement has less number of conditional checks than two successive
ifs.
A)if else If B)if elif c) if-else d)None
4) If the condition is …………. , the statements of if block will be executed otherwise the
statements in the ……….. block will be executed
A)false,true B)true,false C)both qption are true D)can’t say
Worksheet Level - 2
1) How do you check for multiple conditions in a single if statement?
a) if x > 10 and y < 5: b) if x > 10 && y < 5:
c) if (x > 10) && (y < 5): d) if x > 10 & y < 5:
4-Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
weather='raining' a=int{input("ENTER FIRST NUMBER")}
if weather='sunny': b=int(input("ENTER SECOND NUMBER"))
print("wear sunblock") c=int(input("ENTER THIRD NUMBER"))
elif weather='snow': if a>b and a>c
print("going skiing") print("A IS GREATER")
else: if b>a and b>c:
print(weather) Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)
5- Symbol used to end the if statement:
i. Semicolon(;) ii. Hyphen(-) I ii. Underscore( _ ) iv. colon(:)
Worksheet Level - 1
1-How many times will the following loop execute and give the output?
z=7
sum=0;
3-What will be the final value of variable x after the following code is executed ?
x=10
while x>1:
x=x//3
x=x+1
print(x)
5-Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
250 = Number Val = int(rawinput("Value:"))
WHILE Number <= 1000: Adder = 0
if Number => for C in range(1,Val,3)
750 Adder+=C
if C%2=0:
print (Number)
Print (C*10)
Number =
else:
Number + 100 print (C*)
else print (Adder)
print( Number *
2)
Number =
Number + 50
30=To a=”1”
for K in range(0,To) while a>=10:
IF k%4==0: print("Value of a=",a)
print (K*4) a=+1
8- .…………loop is the best when the number of iterations are not known.
i. while ii. do-while iii. for iv. None of these
Worksheet Level - 2
1- What will be printed by the following code when it executes?
sum = 0
values = [1,3,5,7]
for number in values:
sum = sum + number
print(sum)
a)4 b)0 c)7 d)16
output = ""
x = -5
while x < 0:
x=x+1
output = output + str(x) + " "
print(output)
7-What will be the final value of variable x after the following code is executed?
x=10
while x>1:
x=x//3
x=x+1
print(x)
Ans-1
Worksheet Level - 1
1-WRITE A PROGRAM to display all number from 1 to 15.
2. WRITE A PROGRAM to display sum of all numbers from 1 to 10.
3. WRITE A PROGRAM to display Average of numbers from 1 to 10.
4. WRITE A PROGRAM to display multiply all numbers from 1 to 10.
5. WRITE A PROGRAM to display Square all numbers from 1to 20.
6. WRITE A PROGRAM to display Cube all numbers from 1to 100
7. WRITE A PROGRAM to display all odd numbers from 1to 100
8. WRITE A PROGRAM to display all even numbers from 1to 100
9.Take an integer input N from the user. Print N Fibonacci numbers. Recall that Fibonacci
series progresses as 0 1 1 2 3 5 8…
10.Take an integer input N from the user. Find Factorial of N and print it .
11.Print first 10 prime numbers.
Worksheet Level - 2
1.Take an integer input N from the user. Print the table of N.
2.WRITE A PROGRAM to check whether the given number is palindrome or not.
3. Write a program to display all prime numbers within a range.
4- WRITE A PROGRAM that uses exactly four for loops to print the sequence of letters
below.
AAAAAAAAAA *
BBBBBBBBB **
CCCCCCCC ***
EEEEEEE ****
FFFFFF *****
##### 8
#### 86
### 864
## 8642
#
5-Display numbers from -10 to -1 using for loop
6-Use a loop to display elements from a given list present at odd index positions
7-Display numbers from a list using loop
8-Python program to reverse a number
9-Python program to check armstrong number
10-Python program to check leap year
11-Python program to convert celsius to fahrenheit
12-Python program to find factorial of a number
String: Text enclosed inside the single or double quotes referred as String.
String Operations: String can be manipulated using operators like concatenation (+), repetition (*)
and membership operator like in and not in.
Operation Description
Repetition Str * x
Membership in , not in
Slicing String[range]
FUNCTION DESCRIPTION
WORKSHEET LEVEL - 1
6. What is the correct python code to display the last four characters of “Digital India”
i. str[-4:] ii. str[4:] iii. str[*str] iv. str[/4:]
7. Which of the following operator can be used with string data type?
i. ** ii. % iii. + iv. /
8. Naman prepare a code for different conditions and take different inputs in variable str1. What will
be the output for the different inputs given below:
str1="PT1"
str2=" "
I=0
while I<len(str1):
if str1[I]>="A" and str1[I]<="M":
str2=str2+str1[I+1]
elif str1[I]>="0" and str1[I]<="9":
str2=str2+str1[I-1]
else:
str2=str2+"*"
I=I+1
print(str2)
WORKSHEET LEVEL - 2
FUNCTION DESCRIPTION
split() Breaks up a string at the specified separator and returns a list of substrings.
replace() It replaces all the occurrences of the old string with the new string.
find() It is used to search the first occurrence of the substring in the given string.
index() It also searches the first occurrence and returns the lowest index of the substring.
It checks for alphabets in an inputted string and returns True in string contains only
isalpha()
letters.
isalnum() It returns True if all the characters are alphanumeric.
isdigit() It returns True if the string contains only digits.
count() It returns number of times substring str occurs in the given string.
islower() It returns True if all the letters in the string are in lowercase.
isupper() It returns True if all the letters in the string are in uppercase.
lstrip() It returns the string after removing the space from the left of the string
rstrip() It returns the string after removing the space from the right of the string
strip() It returns the string after removing the space from the both side of the string
It returns True if the string contains only whitespace characters, otherwise returns
isspace()
False.
istitle() It returns True if the string is properly title-cased.
swapcase() It converts uppercase letter to lowercase and vice versa of the given string.
ord() It returns the ASCII/Unicode of the character.
chr() It returns the character represented by the imputed Unicode /ASCII number
WORKSHEET LEVEL - 1
print(x.find('P'))
a. -1 c. 1
b. 0 d. 3
11. What will be the output after the following statements?
x = 'Pi Py Python'
print(x.startswith('p'))
a. 1 c. True
b. 0 d. False
12. What will be the output after the following statements?
x = 'Pi Py Python'
print(x.endswith('n'))
a. 1 b. 0
a. 1 c. True
b. 0 d. False
14. What will be the output after the following statements?
x = 'Python 3'
print(x.isnumeric())
a. 1 c. True
b. 0 d. False
WORKSHEET LEVEL - 2
a. SyntaxError c. ValueError
b. TypeError d. NameError
Module – 8
Title – Programs on Strings
WORKSHEET LEVEL - 1
WORKSHEET LEVEL - 2
Page 30 of 60
Module – 9
Title – List Introduction
Page 31 of 60
The individual elements of a list are accessed through their indexes. Consider the following examples:
>>>vowels = *‘a’,’e’,’i',’o’,’u’+
>>>vowels*0+
‘a’
>>>vowels*4+
‘u’
>>>vowels*-1+
‘u’
>>>vowels*-5+
‘a’
Difference from Strings
You cannot change individual elements of a string in place, but Lists allow you to do so. That is, following
statement is fully valid for Lists:
L*i+ = <element>
For example, consider the same vowels list crated above. Now if you want to change some of these vowels, you
may write something as show below:
>>>vowels*0+ = ‘A’
>>>vowels
*‘A’,’e’,’i',’o’,’u’+
Traversing a List
The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:
for<item> in <list>:
<process each item here>
For example, following loop shows each item of list L in separate lines
L = *‘P’,’Y’,’T’,’H’,’O’,’N’+
for a in L:
print(a)
If you only need to use the indexes of elements to access them, you can use
The above loop will produce result as:
functions range() and len() as per the following syntax:
P for index in range(len(L)):
Y <process L*index+ here>
T Program to print elements of a list *‘q’,’w’,’e’,’r’,’t’,’y’+ in separate lines along with
H elements’ both index positive and negative.
O L = *‘q’,’w’,’e’,’r’,’t’,’y’+
N fori in range(len(L)):
print(“Element at positive index”, i, “and negative index”, i-len(L),”is =
“,L*i+)
Comparing List
You can compare two lists using standard comparison operators of Python, i.e., <, >, ==, != etc. Python
internally compares individual elements of lists (and tuples) in lexicographical order. This means that to
compare equal, each corresponding element must compare equal and the two sequences must be of the same
type i.e., having comparable types of values. Consider the following examples:
>>>L1, L2, L3 = *1,2,3+, *1,2,3+, *1, *2,3++
>>>L1 == L2
True
>>>L1==L3
False
Consider the following considering the above two lists
>>>L1<L2
False
>>>L1<L3
TypeError
L1*1+ is integer (2) and L3*1+ is a list *2,3+ and list and numbers and not >>> *1,2,8,9+<*9,1+
comparable types is Python. True
>>> *1,2,8,9+<*1,2,9,1+
True
>>> *1,2,8,9+<*1,2,9,10+
True
>>> *1,2,8,9+<*1,2,8,4+
False Page 32 of 60
Python gives the final result of non-equality comparisons as soon as it gets a result in terms of True/False from
corresponding elements’ comparison. If corresponding elements are equal, it goes on to the next element, and
so on, untill it finds elements that differ. Subsequent elements are not considered.
List Operations
1. Joining Lists
Joining two lists is very easy just like you perform addition. The concatenation operator +, when used
with two or more lists, joins those lists. Consider the example given below
>>>lst1 = *1,3,5+
>>>lst2 = *6,7,8+
>>>lst3 = lst1 + lst2
>>>lst3
*1,3,5,6,7,8+
2. Repeating or Replicating Lists
You can use * operator to replicate a list specified number of times, e.g.
>>>lst1 = *1,3,5+
>>>lst1*3
*1,3,5,1,3,5,1,3,5+ Lists also supports slice steps. That is, if you want to
3. Slicing the Lists extract, not consecutive but every other element of the
List Slices are the sub part of a list extracted out. list, there is a way out – the slice step. The slice are used
You can use indexes of list elements to create list as per following format
slices as per following format: seq = L*start:stop:step+
Consider some examples to understand this.
seq = L*start:stop+
>>>lst = *10,12,14,20,22,24,30,32,34+
The above statement will create a list namely seq
>>>lst*0:10:2+
having elements of list L on indexes start, start+1, *10.14.22.30.34+
start+2,…..,stop-1. Index on last limit is not >>>lst*2:10:3+
included in the list slice. The list slice is a list in *14,24,34+
itself, that is, you can perform all operations on it >>>lst*::3+
just like you perform on lists. Consider the *10,20,30+
following example:
>>>lst = *10,12,14,20,22,24,30,32,34+
>>>seq = lst*3:-3+
>>>seq
*20,22,24+
>>>seq*1+ = 28
>>>seq
*20,28,24+
Using Slices for List Modification: You can use slices to overwrite one or more list elements with one
or more other elements. Following example will make it clear to you:
>>>L = *“One”, “Two”, “Three”+
>>>L*0:2+ = *0,1+
If you give a list slice with range much
>>>L outside the length of the list, it will
*0,1,”Three”+ simply add the values at the end. E.g.:
>>>L = *“One”, “Two”, “Three”+ >>>L1 = *1,2,3+
>>>L*0:2+ = “a” >>>L1*10:20+ = “abcd”
>>>L >>>L1
*“a”,”Three”+ *1,2,3,’a’,’b’,’c’,’d’+
Page 33 of 60
You can also add items to an existing sequence. The append() method adds a single item to the end of the list.
It can be done as per following format:
L.append(item)
Consider some examples:
>>>lst1 = *10,12,14+
>>>lst1.append(16)
>>>lst1
*10,12,14,16+
Updating/Modifying elements to a list
To update or change an element of the list in place, you just have to assign new value to the element’s index in
list as per syntax:
L*index+ = <new value>
Consider following examples
>>>lst1 = *10,12,14,16+
>>>lst1*2+ = 24
>>>lst1
*10,12,24,16+
Deleting Elements from a List
You can also remove items from lists. The del statement can be used to remove an individual item or to remove
all items identified by a slice. It is to be used as per syntax given below:
del List*<index>+
You can also use pop() method to remove single
del List*<start>:<stop>+ element, not list slices. The pop() method removes an
Consider the following examples: individual item and returns it. The del statement and
>>>lst=*1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20+ the pop method do pretty much the same thing,
>>>del lst*10+ except that pop() method also returns the removed
>>>lst item along with deleting it from list. The pop() method
*1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20+ is use as per the following format:
>>>del lst*10:15+ List.pop(<index>)
>>>lst Where <index> is optional and if skipped, last element
is deleted. Consider examples
*1,2,3,4,5,6,7,8,9,10,17,18,19,20+
>>>lst = *1,2,3,4,5,6,74,8+
If you use del<lstname> only, e.g. del lst, it will delete all >>>lst.pop()
the elements and the list object too. After this, no object by 8
the name lst would be existing. >>>lst.pop(5)
6
List Functions and Methods The pop() method is useful only when you want to
store the element being deleted for later use. E.g.
1. len() function >>>item1 = L.pop()
This function returns the length of a list i.e. this
function returns number of elements present in the list. It is used as per following format:
len(<list>)
For example for a list L1 = *13,18,11,16,18,14+
len(L1) will return 6
2. list() function
This function converts the passed argument to a list. The passed argument could be a string, a list or
even a tuple. It is used as per following format:
list(<argument>)
For example for a string s = “Computer”
list(s) will return *‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’+
3. The append() method
The append() method adds an item to the end of the list. It works as per following syntax:
List.append(<item>)
For example, to add a new item “yellow” to a list containing colours, you may write:
>>>colours = *“red”,”green”,”blue”+
>>>colours.append(“yellow”)
>>>colours
*“red”,”green”,”blue”,”yellow”+
Page 34 of 60
4. The extend() method
The extend() method is also used for adding multiple elements (given in the form of a list) to a list. The
extend() function works as per following format:
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to the
list object on which extend() is applied. Consider following example:
>>>t1=*‘a’,’b’,’c’+
>>>t2=*‘d’,’e’+
>>>t1.extend(t2)
>>>t1
*‘a’,’b’,’c’,’d’,’e’+
>>>t2
*‘d’,’e’+
5. The insert() method
If you want to insert an element somewhere in between or any position of your choice, both append()
and extend()are of no use. For such a requirement insert() is used.
The insert() function inserts an item at a given position. It is used as per following syntax:
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to be
added. Consider the following example:
>>>t1=*‘a’,’e’,’u’+
>>>t1.insert(2,’i')
>>>t1
*‘a,’e’,’i',’u’+
For function insert(), we can say that:
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() method
This function returns the count of the item that you passed as argument. If the given item is not in the
list, it returns zero. It is used as per following format:
List.count(<item>)
For instance:
>>>L1 = *13,18,20,10,18,23+
>>>L1.count(18)
2
>>>L1.count(28)
0
7. The Index() method
This function returns the index of first matched item from the list. It is used as per following format:
List.index(<item>)
For example, for a list L1 = *13,18,11,16,18,14+
>>>L1.index(18)
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() method
The remove() method removes the first occurrence of given item from the list. It is used as per
following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
>>>t1=*‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’+
>>>t1.remove(‘a’)
>>>t1
*’e’,’i',’p’,’q’,’a’,’q’,’p’+
>>>t1.remove(‘p’)
>>>t1
*’e’,’i',’q’,’a’,’q’,’p’+
Page 35 of 60
>>>t1.remove(‘k’)
ValueError
9. The pop() method
The pop() is used to remove the item from the list. It is used as per the following syntax:
List.pop(<index>)
Thus, pop() removes an element from the given position in the list, and return it. If no index is
specified, pop() removes and returns the last item in the list.
>>>t1 = *‘k’,’a’,’i',’p’,’q’,’u’+
>>>ele = t1.pop(0)
>>>ele
‘k’
10. The reverse() method
The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list. The
syntax to use reverse method is:
List.reverse()
For example:
>>>t1 = *‘e’,’i',’q’,’a’,’q’,’p’+
>>>t1.reverse()
>>>t1
*‘p’,’q’,’a’,’q’,’i',’e’+
11. The sort() method
The sort() function sorts the items of the list, by default in increasing order. This is done “in place” i.e.
it does not create a new list. It is used as per following syntax:
List.sort()
For example:
>>>t1 = *‘e’,’i',’q’,’a’,’q’,’p’+
>>>t1.sort()
>>>t1
*‘a’,’e’,’i',’p’,’q’,’q’+
To sort a lit in decreasing order using sort(), you can write:
>>>List.sort(reverse=True)
12. min() Function
This function returns the minimum value present in the list. This function will work only if all elements
of the list are numbers or strings. This function gives the minimum value from a given list. Strings are
compared using its ordinal values/Unicode values. This function is used as per following format:
min(<list>)
For example L1 = *13,18,11,16,18,14+ and L2 = *‘a’, ‘e’ ‘i', ‘o’ ,’U’+ then
min(L1) will return 11 and min(L2) will return ‘U’
13. max() Function
This function returns the maximum value present in the list. This function will work only if all elements
of the list are numbers or strings. This function gives the maximum value from a given list. Strings are
compared using its ordinal values/Unicode values. This function is used as per following format:
max(<list>)
For example L1 = *13,18,11,16,18,14+ and L2 = *‘a’, ‘e’ ‘i', ‘o’ ,’U’+ then
max(L1) will return 18 and max(L2) will return ‘o’
14. sum() Function
This function returns the total of values present in the list. This function will work only if all elements
of the list are numbers. This function gives the total of all values from a given list. This function is used
as per following format:
sum(<list>)
For example L1 = *13,18,11,16,18,14+ then sum(L1) will return 90
15. The clear() method
This method removes all the items from the list and the list becomes empty list after this function.
This function returns nothing. It is used as per following format:
List.clear()
Page 36 of 60
For instance:
>>>L1=*2,3,4,5+
>>>L1.clear()
>>>L1
*+
WORKSHEET LEVEL - 1
WORKSHEET LEVEL – 2
Page 37 of 60
d. *L*1++ + L*3+
e. L*4:+
f. L*0:2+
6. What does each of the following expressions evaluate to? Suppose that L is the list:
*“These”, *“are”, “a”+, *“few”, “words”+, “that”, “we”, “will”, “use”+
a. len(L)
b. L*3:4+ + L*1:2+
c. “few” in L*2:3+
d. “few” in L*2:3+*0+
e. “few” in L*2+
f. L*2+*1:+
g. L*1+ + L*2+
7. What does a+b amounts to if a and b are lists?
8. What does a*b amounts to if a and b are lists?
9. What does a+b amounts to if a is a list and b = 5?
10. Which functions can you use to add elements to a list?
11. What is the difference between append() and insert() methods of list?
12. What is the difference between append() and extend() methods of list?
13. What does list.clear() function do?
14. L is a non-empty list of ints. Print the smallest and largest integer in L. Write the code without using a
loop.
15. Write the most appropriate list method to perform the following tasks:
a. Delete a given element from the list.
rd
b. Delete 3 element from the list.
c. Add an element in the end of the list.
d. Add an element in the beginning of the list.
e. Add elements of a list in the end of a list.
16. Write a program to find the second largest number of a list of numbers.
Page 38 of 60
Module – 10
Title – Programs on lists without list modification
WORKSHEET LEVEL – 1
Q.1 . Write a program in python to search the index of the element 400 from the given list. The
given list are as follows: LST=*100,200,300,400,500,’Raman’,100,’Ashwin’+
Q.2.Write a program in python to find whether the element is present in the given list. The given list
are as follows: LST=*100,200,300,400,500,’Raman’,100,’Ashwin’+
Q.3.Write a program in python to return the elements with maximum values from the given list. The
given list is:
LST=*10,20,30,40+.
Q.4.Write a program in python to return the elements with minimum values from the given list. The
given list is:
LST=*10,20,30,40+.
Q.5 Write a program in python to find the sum of all the elements in a list.
Q.6. Write a program in python to count total number of element in a list.
WORKSHEET LEVEL – 2
Q.1 . Write a program in python to search the index of the element 400 from the given list. The
given list are as followes: LST=*100,200,300,400,500,’Raman’,100,’Ashwin’+
Q.2.Write a program in python to find whether the element is present in the given list. The given list
are as followes: LST=*100,200,300,400,500,’Raman’,100,’Ashwin’+
Q.3.Write a program in python to return the elements with maximum values from the given list. The
given list is:
LST=*10,20,30,40+.
Q.4.Write a program in python to return the elements with minimum values from the given list. The
given list is:
LST=*10,20,30,40+.
Q.5. Write a program in python to return the elements with minimum values from the given list. The
given list is:
LST=*‘A’, ’a’, ’B’, ’C’+.
Q.6 Write a program in python to find the sum of all the elements in a list.
Q.7. Write a program in python to count total number of element in a list.
Q.8.Write a program in python to access the elements of a list using while loop.
Q.9.Write a program in python to find at least one common element against the two inputted list.
Page 39 of 60
Module – 11
Title – Programs on lists with list modification
WORKSHEET LEVEL – 1
WORKSHEET LEVEL – 2
Page 40 of 60
Module – 12
Title – Tuples
Tuples – Introduction:
Tuple is a collection of objects separated by commas.
It consists of ordered, immutable collections of items.
Tuples are enclosed within parentheses ( ).
Tuples can contain values of mixed data types.
Index of first item is 0 and the last item is n-1. Here n is number of items in a Tuple.
Creation of Tuple:
The difference between tuples and lists is that tuples are immutable while lists are mutable.
Therefore, it is possible to change a list but not a tuple. The literal syntax of list is shown by the *+
whereas tuple is shown by the (). The List has a variable length while tuple has the fixed length.
Lists are used for data that needs to be changed frequently, while tuples are used for data that
doesn't need to be changed frequently.
Accessing Tuples:
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
T* i + returns the item present at index i.
For Example-
>>>T=(5,10,15,20,25,30,35,40)
>>>T*0+ #shows 0 index element i.e. 5
>>>T*4+ #shows Fifth element of tuple i.e. 25
>>>T*-3+ #Backward indexing, Shows similar to >>>T*5+ i.e. 30
>>>T*10+ #returns error as index is out of range (IndexError)
Page 41 of 60
>>> s * 3
(2,4,6,2,4,6,2,4,6)
Membership in and not in >>> t1 = (‘W’, 'R’, 'G', ‘P’, 'B’)
>>> 'G’ in t1 True
>>> 'C' in t1 False
Slicing Tuple*range+ t=(10,20,30,40,50,60,70,80,90,100)
Tuple_name*start:stop:step+ >>> t*2:6:1+
(30, 40, 50, 60)
>>> t* : 5:1+
(10, 20, 30, 40, 50)
>>> t* : : -1+
(100, 90, 80, 70, 60, 50, 40, 30, 20, 10)
Page 42 of 60
del() Tuple is of immutable type so it is not possible to >>> t1 = (10,100,50,60,30,40)
delete an individual element of a tuple. With >>> del (t1)
del() function, it is possible to delete a complete
tuple.
Worksheet Level - 1
MULTIPLE CHOICE QUESTIONS :
2. Jyoti wants to add a new tuple t2 to the tuple t1, which statement she should use-
i. sum(t1,t2) ii. T1.add(t2) iii. t1+t2 iv. None of these
6. To display the last element of the tuple, which statement should be used-
i>>> t.display() ii>>>t.pop() iii>>>t[-1] iv>>>t.last()
Worksheet Level - 2
MULTIPLE CHOICE QUESTIONS :
1. Which of the following is a Python tuple?
i. [1, 2, 3] ii. (1, 2, 3) iii. {1, 2, 3} iv. { }
2. Jyoti wants to add a new tuple t2 to the tuple t1, which statement she should use-
i. sum(t1,t2) ii. T1.add(t2) iii. t1+t2 iv. None of these
Page 43 of 60
3. Which of the following is correct to insert a single element in a tuple-
i. T=4 ii. T=(4) iii. T(4,) iv. T=[4,]
7. Rajat wants to delete all the elements from the tuple, which statement he should use to perform this
operation-
i t.clear() ii. del t iii. t.remove() iv. None of these
8. To display the last element of the tuple, which statement should be used-
i>>> t.display() ii>>>t.pop() iii>>>t[-1] iv>>>t.last()
9. Shreya wants to add a new tuple t2 to the tuple t1, which statement she should use
i. sum (t1,t2) ii. t2.add(t1) iii. t1+t2 iv. None of these
10. Which of the following operations is not valid for tuples in Python?
i. Concatenation ii. Indexing iii. Appending iv. Slicing
Answer: 1- ii, 2-iii, 3-iii, 4-ii, 5-iii, 6-i, 7- iv, 8-iii, 9-iii, 10-iii
Page 44 of 60
Module – 13
Title – Dictionary Introduction
DICTIONARY
Dictionaries are used to store data v alues in key: value pairs.
They are surrounded by curly brackets(, -)
Dictionaries in python are Unordered.
Each Key Value Pair is separated by a colon ( : ) .
Dictionaries can store heterogeneous data.
Keys in Python Dictionary are immutable while
values are mutable.
Creating a Dictionary
student = , - #Creates an empty Dictionary
Dict = dict(,1: 'East', 2: 'West', 3:'North', 4: ‘South’-) #Creates a Dictionary with dict()
method
DICTIONARY OPERATIONS
1. Traversing a Dictionary:
To travel through all the key: value pairs and process each element for loop can be
used as per the following syntax:
Page 45 of 60
Syntax: for <key> in <dictionary_name>: Syntax: for <key> in <dictionary_name>.keys():
statements statements
Example: for key in Dict: Example: for key in Dict.keys():
Print (key, ‘:’,Dict*key+) Print (key,’:’, Dict*key+)
Output: 1: 'East' Output: 1: 'East'
2: 'West', 2: 'West',
3:'North' 3:'North'
4: ‘South’ 4: ‘South’
5: ‘South East’ 5: ‘South East’
OR
Page 46 of 60
WORKSHEET LEVEL – 1
WORKSHEET LEVEL – 2
Page 47 of 60
Module – 14
Title – Dictionary – Methods, functions and programs
Dictionary methods and functions:
Page 48 of 60
max(D1)
Output: 3
Programs on Dictionaries-
1. Write a program to enter names of employees and their salaries as input and store
them in a dictionary.
d = ,-
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter employee name: ")
sal = float(input("Enter employee salary: "))
d*name+ = sal
ans = input("Do you want to enter more employee names? (y/n)")
print(d)
D2 = ,-
for key in D1:
num = sum(D1*key+)
D2*key+ = num
Page 49 of 60
print(D2)
3. Write Python code to create following dictionary and check for the value of an
existing key.
,0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"-
dict1=,0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"-
ans='y'
while ans=='y' or ans=='Y':
val=input("Enter Vlue: ")
print("Value ",val, end=" ")
for k in dict1:
if dict1*k+ == val:
print("Exists at ",k)
break;
else:
print("Not Found")
ans=input("Want to check another value:(y/n)? :- ")
4. Write a Python Program to display the frequency of the number of times a number
appears in the list using a dictionary.
list1 = *1, 2, 3, 4, 1, 2, 3, 4, 5, 5, 5+
frequency_dict = ,-
for number in list1:
if number in frequency_dict:
frequency_dict*number+ += 1
else:
frequency_dict*number+ = 1
WORKSHEET LEVEL – 1
Page 50 of 60
1. What will be the output of the following code fragments:
a. aDict = ,‘Bhavna’:1, ‘Richard’:2, “Firoza”:10, “Arshnoor”:20-
temp=0
for key in aDict:
if temp<key:
temp=key
print(temp)
b. aDict = ,‘Bhavna’:1, ‘Richard’:2, “Firoza”:10, “Arshnoor”:20-
temp = “”
for key in aDict:
if temp<key:
temp=key
print(temp)
c. aDict = ,‘Bhavna’:1, ‘Richard’:2, “Firoza”:10, “Arshnoor”:20-
k=”Bhavna”
v=-1
if k in aDict:
aDict*k+=v
print(aDict)
2. The membership operator (in & not in) only works with keys of a dictionary but to check for the
presence of a value in a dictionary, you need to write a code. Write a Python program that takes a
value and checks whether the given value is part of given dictionary or not. If it is, it should print the
corresponding key otherwise print an error message.
WORKSHEET LEVEL – 2
Page 51 of 60
Name
Ryna
Subject(key) Marks (value)
1 40
2 50
3 60
Name
Zeba
Subject(key) Marks (value)
1 70
2 80
3 90
Name
Suniti
Subject(key) Marks (value)
1 40
2 70
3 70
Page 52 of 60
Module – 15
Title – Introduction to Python Modules
Python Module A module is a logical organization of Python code. Related code are grouped
into a module which makes the code easier to understand and use.
Any python module is an object with different attributes which can be bind and referenced.
Simply, it is a file containing a set of functions which can be included in our application.
commenly used modules
math
random
statistics
import < module_name) # The whole library functions are available in the program
from <module_name> import < function_name> # only single function is available in the
program for use
using alias
math module
Frequently
used Constants
sqrt() functions in abs()
math module pi
ceil() fabs() e
math.pi
Page 53 of 60
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
The ceil() function approximates the given number to the smallest integer, greater than or equal to
the given floating point number.
>>>math.ceil(4.5867)
The floor() function returns the largest integer less than or equal to the given number.
>>>math.floor(4.5687)
math.pow()
The math.pow() method receives two float arguments, raises the first to the second and returns the
result. In other words, pow(2,3) is equivalent to 2**3.
>>>math.pow(2,4)
16.0
>>> math.fabs(-5.5)
5.5
The random module is a built-in module to generate the pseudo-random variables of integers
and float types
It can be used to get a random number, selecting a random elements from a list, shuffle
elements randomly, etc
Page 54 of 60
x= random.randint(a,b) # here x is an integer , a<=x<=b
ii) random.randrange(a,b)
It will generate an integer between a and b including a and b
x= random.randrange(a,b)
# here x is an integer , a<x<b, with increment 1
randrange can also be used to generate value after certain interval
import random
print(random.random())
print(random.randint(1, 100))
print(random.randint(1, 100))
print(random.randrange(1, 10))
print(random.randrange(1, 10, 2))
print(random.randrange(0, 101, 10))
import statistics as st
print(st.mean(*1,2,3,4,5+))
print(st.median(*1,2,3,4,5+))
print(st.mode(*1,2,3,1,2,2,4,5+))
output:
3
3
2
Page 55 of 60
WORKSHEET LEVEL 1
Page 56 of 60
(a) 30 @ (b) 10@20@30@40@50@
(c) 20@30 (d) 40@30@
11 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=”#“)
a) 10#40#70# b) 30#40#50#
c) 50#60#70# d) 40#50#70#
12 Observe the following Python code and find out which of the given options (i) to (iv) are
theexpected correct output(s). Also, assign
maximum and minimum values that can beassigned to the variable ‘Go’.
import random
X=[100,75,10,125]
Go =random.randint(0,3)
for i in range(Go):
print(X[i],"$$")
a) 100$$ b) 100$$
75$$ 99$$
10$$
c) 150$$ d) 125$$
100$$ 10$$
WORKSHEET LEVEL 2
Page 57 of 60
c) To interact with the operating system
d) To manipulate strings
6 Which of these definitions correctly describes a module?
a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code
7 Which of the following is not an advantage of using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
8 Which of the following is true about top-down design process?
a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed
9 In top-down design every module is broken into same number of submodules.
a) True b) False
10 To include the use of functions which are present in the random library, we must use the option:
a) import random b) random.h
c) import.random d) random.random
11 The output of the following Python code is either 1 or 2.
import random
random.randint(1,2)
a) True b) False
12 What is the interval of the value generated by the function random.random(), assuming that the
random module has already been imported?
a) (0,1) b) (0,1+
c) *0,1+ d) *0,1)
13 What will be the output of the following Python code?
random.randrange(0,91,5)
a) 10
b) 18
c) 79
d) 95
14 Which of the following cannot be returned by random.randrange(4)?
a) 0
b) 3
c) 2.3
d) none of the mentioned
15 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@
16 AR=*20,30,40,50,60,70+
Page 58 of 60
Lower =random.randint(1,4)
Upper =random.randint(2,5)
for K in range(Lower, Upper +1):
print (AR*K+,end=”#“)
a) 10#40#70# b) 30#40#50#
c) 50#60#70# d) 40#50#70#
17 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)
for k in range(From,To+1):
print(ar*k+,end=”#”)
a) 10#40#70# b) 50#60#70#
c) 30#40#50# d) 40#50#70#
18 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 minimum and maximum values that
can be assigned to the variable End .
import random
Colours = *"VIOLET","INDIGO","BLUE","GREEN","YELLOW","ORANGE","RED"+
End = randrange(2)+3
Begin = randrange(End)+1
for i in range(Begin,End):
print(Colours*i+,end="&")
a) INDIGO&BLUE&GREEN& b) VIOLET&INDIGO&BLUE&
c) BLUE&GREEN&YELLOW& d) GREEN&YELLOW&ORANGE&
19 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code?
import random
X= random.random()
Y= random.randint(0,4)
print(int(),":",Y+int(X))
a) 0:5 b) 0:3
c)0:0 d) 2:5
20 Observe the following Python code and find out which of the given options (i) to (iv) are
theexpected correct output(s). Also, assign
maximum and minimum values that can beassigned to the variable ‘Go’.
import random
X=[100,75,10,125]
Go =random.randint(0,3)
for i in range(Go):
print(X[i],"$$")
a) 100$$ b) 100$$
75$$ 99$$
10$$
c) 150$$ d) 125$$
Page 59 of 60
100$$ 10$$
21 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 first, second and third.
from random import randint
LST=*5,10,15,20,25,30,35,40,45,50,60,70+
first = randint(3,8)
second = randint(4,9)
third = randint(6,11)
print(LST*first+,"#", LST*second+,"#", LST*third+,"#")
a) ) 20#25#25# b) 30#40#70#
c) 15#60#70# d) 35#40#60#
22 Give output for the following code:
import random
p=’Practice Session'
i=0
while p[i]!='y':
t=random.randint(0,3)+5
print(p[t],'-')
i=i+1
***************
Page 60 of 60