[go: up one dir, main page]

0% found this document useful (0 votes)
251 views60 pages

XII - CS - Bridge Course

Uploaded by

Abhilasha Kumari
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)
251 views60 pages

XII - CS - Bridge Course

Uploaded by

Abhilasha Kumari
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/ 60

BRIDGE COURSE

FOR
CLASS XII

SUBJECT : COMPUTER SCIENCE

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

CONTENT DEVELOPMENT TEAM


Smt. Neetu Saxena, PGT (Comp. Sc.), KV No. 1 Shahjahanpur Cantt 1st Shift
Sh. Nitin Rathore, PGT (Comp. Sc.), KV IFFCO Bareilly
Sh. Ashish Kumar Vaish, PGT (Comp. Sc.), KV SGPGI Lucknow
Sh. Someshwar Nath Srivastav, PGT (Comp. Sc.), KV Lakhimpur Kheri 1st Shift
Smt. Sonali Dhoundiyal, PGT (Comp. Sc.), KV OCF Shahjahanpur 2nd Shift

Bridge Course XII – Computer Science Page 3 of 60


TABLE OF CONTENT
MODULE NO. MODULE TITLE PAGE NO.

1 Python Introduction Part – 1 4

2 Python Introduction Part – 2 9

3 Conditional Statements 13

4 Looping Statements 16

5 Programs on Loops 20

6 String Introduction 21

7 String Methods and Functions 25

8 Programs on Strings 29

9 List Introduction 30

10 Programs on list without list modification 38

11 Programs on list with list modification 39

12 Tuples 40

13 Dictionary Introduction 44

14 Dictionary – Methods, Functions and Programs 47

15 Introduction to Python Modules 52

Bridge Course XII – Computer Science Page 4 of 60


Module – 1
Title – Python Introduction Part - I

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 single line comment

‘’’ this is a

Mulitiline comment ‘’’

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)

Tokens: The Language's Alphabet: Smallest unit of a program

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., +, -, *, /).

Bridge Course XII – Computer Science Page 5 of 60


 Literals:Values that represent fixed data (e.g., integers, floating point , strings, boolean).
 Punctuators: Symbols used for delimitation and structuring code (e.g., parentheses,
brackets, braces)

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?

4. Identify valid or invalid identifiers:


i. True
ii. Student-Name
iii. IF
iv. PRINT
v. 1stAge
vi. Number1

5.The default separator character for print is


a)tab b)space c)newline d)dot

6.The lines ignored by the compiler and not executed are called
a)operators b)operands c)functions d)comments

7.What will be the value of the following Python expression?


4 + 5%5

8. Which of the following character is used to give single-line comments inPython?


a) // b) # c) ! d) /*

9. . dentify each of the following whether mutable and immutable :


i. X= “Great India”
ii. Y= , 1: “Monday”, 3: “Wednesday”, 5: “Friday”, 7: “Sunday” -
iii. Z= *“a”,”e”, “i”, “o”, “u”+
iv. W= (“Rakesh”, “Rajesh”, “Ravindra”, “Pawan”, “Santosh”)

10.find the error:


scale=90
Print scale

Bridge Course XII – Computer Science Page 6 of 60


11. Correct the following program so that it displays 33 when 30 is input:
val=input(“Enter a value”)
nval=val+3
print(nval)

12. Which of the following is the truncation division operator in Python?


a) |
b) //
c) /
d) %

13. find the error:


if 5 > 2:
print("Five is greater than two!")if 5 > 2:
print("Five is greater than two!")

14. Evaluate:
2+3//4-7

15. Evaluate:”cs”**10%3

Bridge Course XII – Computer Science Page 7 of 60


Worksheet Level - 2

1. Find the error


t=7
if t>3:
print(“value is less than 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

3. Which of the following are keywords?a)name


b)Print c)print d)input

4. Which of the following are valid identifiers?a)odd even b)odd_even c)print d)odd-even

5. The default separator character for print is


a)tab b)space c)newline d)dot

6.The lines ignored by the compiler and not executed are calleda)operators b)operands c)functions
d)comments

7.What will be the value of the following Python expression?


4+3%5

8. Which of the following character is used to give single-line comments inPython?


a) // b) # c) ! d) /*

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


i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
123
b) error
c) 1 2
d) none of the mentioned
10.find the error:
Temperature=90
Print Temperature

11. Correct the following program so that it displays 33 when 30 is input:val=input(“Enter a

Bridge Course XII – Computer Science Page 8 of 60


value”)
nval=val+3
print(nval)

12. Which of the following is the truncation division operator in Python?


e) |
f) //
g) /
h) %

13. find the error:


if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

14. Evaluate:
2+3//4-7

15. Evaluate:
”cs”**10%3

(SHORT ANSWER TYPES)


1. Create a variable named carname and assign the value Volvo to it
2. How many types of strings are supported by Python?Ans.
3. How can you create multi-line strings in Python?
4. Write a Program to obtain temperature in Celsius and convert it intoFahrenheit
using formula – C X 9/5 + 32 = F
5. Predict output:
a,b,c=2,3,4
a,b,c=a*a,a*b,a*c
print(a,b,c)
6. WAP to print the area of circle when radius of the circle is given by user
7. WAP to read a number in n and prints n2 , n3 , n4
8.WAP to find the area of a triangle.

Bridge Course XII – Computer Science Page 9 of 60


Module – 2
Title – Python Introduction Part – II

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

Arithmetic Operators +, -, /, //, % *

Relational Operators >, <, >=, <=, ==, !=

Logical Operators and, or, not

Assignment operators =, +=, -+, *=, /=,//= , 5=

Membership Operators in, not in

Identity Operators is, is not

Similar category of operators are evaluated from left to right in an expression.

Bridge Course XII – Computer Science Page 10 of 60


Expression is any valid combination of identifiers, literals and operators which evaluates to
single value
X= 2*B+C
Here X , B, C are identifiers and 2 is integer literal

Python Type Conversion


In programming, type conversion is the process of converting data of one type to another.
This can be achieved in two ways

Implicit Type conversion


• By the Python program automatically.

Explicit Type conversion


• The programmer must perform this task manually.
• In Explicit Type Conversion, users convert the data type of an
object to required data type.
• We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
• This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.

Examples:

Implicit Type conversion

c automatically assigned the


higher data type to avoid data
loss

Explicit Type Conversion

Bridge Course XII – Computer Science Page 11 of 60


Worksheet Level - 1
1 Find the output of the following code snippet:
X=y=z=8
print(y)
a) X b) 8 c) y d)z
2 Which is the correct output of the following statements:
X=’24’+ ‘16’
a) 21 b) 40 c) 2416 d)46
3 Which is not the correct way of assignment?
a) A=b=c=89 b) a=6,b=8 c) a,b,c=1,2,3 d)None of
above
4 What is the return type of function eval()?
a) float b) string c) int d)None of the above
5 What is the average value of the code that is executed below?
>>grade=80
>>grade2=90
>>average=(grade+grade2)/2
a) 85.0 b) 85.1 c) 95.0 d)95.1
6 Write the Python expressions for each situation as described below:
a) Increase the value of variable count by 2
b) Assign the value 3 to variables C1,C2,C3
7 What is the result of the following expressions when length equals to 8, width equals to 3 and
height equals to 2.25?
a=8, b=3, c=2.25
i) a/b
ii) a+3/4
iii) a%b
iv) a*b+c/2
8 Mohan is studying on Python data types discussed above . He has learnt all the concepts
Now answer the following questions based on above topic
a) Which datatype will he used to store week days name?
i) List ii) string iii) tuple iv) dictionary
b) Which datatype will he use to store area of his father’s plot
i) float ii) string iii) tuple iv) dictionary
c) Which datatype will he used to store number of houses in the colony?
ii) List ii) int iii) tuple iv) dictionary
d) Which datatype will he use to store name of his friend ‘Ajay’ along with his mobile no?
ii) float ii) string iii) tuple iv) dictionary

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?

Bridge Course XII – Computer Science Page 12 of 60


i) mutable ii) immutable iii) None iv) None of these
d) Which of the following datatype will he use to keep information about whether a child
is studying in his school or not?
iii) complex ii) string iii) boolean iv) dictionary
2 Write a program to find the total surface area of a sphere. The radius is given by the user.
3 Write a python code to read two integers and find the quotient and remainder value
4 Write a program to read three numbers and find their average.
5 Write python program to sWrite a program two numbers without using third number.
Choose options for answering Assertion and Reason based question
a) Both Assertion (A) and Reason ( R )are true and Reason( R ) is the correct explanation of
Assertion (A)
b) Both Assertion (A) and Reason ( R )are true and Reason( R ) is not the correct
explanation of Assertion (A)
c) Assertion (A) is true and Reason ( R ) is false
d) Assertion (A) is false and Reason ( R ) is true.
6 Assertion (A): In Python each character of the string is assigned two-way indices (forward and
backward).
Reason (R): String are the sequences of characters where their indices start with 1 (one) in the
direction and with -1 in the backward direction.
7 Assertion (A): Python lists allows to modify their elements by indexes easily.
Reason (R): Python lists are mutable.
8 Assertion (A): Dictionaries are mutable.
Reason (R): Contents of the dictionary cannot be changed after it has been created.

Bridge Course XII – Computer Science Page 13 of 60


Module – 3
Title – Conditional Statements

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

Bridge Course XII – Computer Science Page 14 of 60


Consider the following code:
if num<0:
print(num, “is a negative number”)
elif num==0:
print(num, “is equal to zero”)
else:
print(num, “is a positive number”)

Worksheet Level - 1
1)The ……………… statement forms the selection construct in Python.
A)if else B)if C)for d)For

2) Can we write if/else into one line in python?

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

5) Which of following is not a decision-making statement.


A)if-else statement B)for statement C)if-else statement D)if statement

6) Can an if statement contain only an else clause without elif?


a) Yes b) No c) Only inside a function d) Only if there is no code in the else clause

7)What is the result of the following code?


x=5
if x > 10:
print("A")
else:
if x > 7:
print("B")
else:
print("C")
a) A b) B c) C d) No output

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:

Bridge Course XII – Computer Science Page 15 of 60


2) Predict the output of the following code:
x=3
if x>2 or x<5 and x==6:
print("ok")
else:
print("no output")
a)ok b)okok c)no output d)none of these

3)Rewrite the code after correcting errors: -


if N=>0
print(odd)
else
Print("even"

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

6-Which of the following is true about nested if-else statements?


a)They cannot be used in Python b)They allow multiple conditions to be checked
c)They are always more efficient than regular if-else statements d)They can only have one level of
nesting

7- What is the output of the following code snippet?


x = 10
if x > 5:
if x < 15:
print('x is between 5 and 15')
else:
print('x is greater than or equal to 15')
else:
print('x is less than or equal to 5')

a)x is between 5 and 15 b)x is greater than or equal to 15


c)x is less than or equal to 5 d)Error

Bridge Course XII – Computer Science Page 16 of 60


Module – 4
Title – Looping Statements
The for Loop
The for loop of Python is designed to process the items of any sequence, such as a list or a
string, one by one. The general form of for loop is as given below:
for <variable> in <sequence>:
<statements to repeat>
For example, consider the following loop:
for element in *10,15,20,25+:
print(element + 2, end = ‘ ‘)
The above loop would give output as:
12 17 22 27

Example 1: Write a program to print cubes of numbers in the range 15 to 20.


for i in range(15,21):
print(“Cube of Number”, i, “=”,i**3)
Example 2: Write a program to print square root of every alternate number in range 1 to 10.
for i in range(1,10,2):
print(“Square root of Number”, i, “=”,i**0.5)
The while Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true. The general form of Python while loop is:
while <logical expression>:
<loop body>
Where the loop-body may contain a single statement or multiple statements or an empty
statement (pass statement). The loop iterates while the logical expression evaluates to true.
When the logical expression becomes false, the program control passes to the line after the
loop-body.
Example: Write a program that multiplies two integers without using * operator, i.e. by
repeated addition.
n1 = int(input(“Enter first number:”))
n2 = int(input(“Enter second number:”))
product = 0
count = n1
while count>0:
product = product + n2
count = count – 1
print(“The product of”, n1, “and”, n2, “=”, product)

Worksheet Level - 1
1-How many times will the following loop execute and give the output?
z=7
sum=0;

Bridge Course XII – Computer Science Page 17 of 60


while z<=12:
sum=sum+z
z=z+2
print(z)
a. 3 times, output-13 (b) 3 times,output-12 (c) 4 times,output-11 (d) 4 times,output-
12

2-How many asterisks does the following code fragment print?


for a in range(-100, 100):
print('*', end='')
print()

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)

4-Predict the output


t2=("sun","mon","tue","wed","thru","fri")
if "sun" in t2:
for i in range (0,3):
print(t2[i])
else:
for i in range (3,6):
print(t2[i])

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

Bridge Course XII – Computer Science Page 18 of 60


Else: print (K+3)

6- What is the output of the following code:


for i in range(-3,4,2):
print(i, end = '$'
7- Write the output of the following code:
Text="@Shop2HomeDelivery"
L=len(Text)
n=""
for i in range(0,L):
if Text[i].isupper():
n=n+Text[i].lower()
elif Text[i].isalpha():
n=n+Text[i].upper()
else:
n=n+'##'
print(n)

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

2- What will be the output of this program?


a = "123789"
while x in a:
print(x, end=" ")
a)xxxxxx b)123789 c)syntax error d)Name error

3- What will be the output of this program?


x=1
while True:
if x % 5 = = 0:
break
print(x)
x+=1
a)error b)21 c)031 d)None of these
4- What does the following code print?

output = ""
x = -5
while x < 0:
x=x+1
output = output + str(x) + " "
print(output)

Bridge Course XII – Computer Science Page 19 of 60


a)5 4 3 2 1 b)-4 -3 -2 -1 0 c)-5 -4 -3 -2 -1 d)this is an infinte loop

5- What will be the output of this statement?


i=0
while i < 3:
print(i)
i += 1
else:
print(0)
a. 01 b)0 1 2 c) 0 1 2 0 d)0 1 2 3

6-What is the output of the following code snippet?


def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
M[i]//=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
a) 5#8#15#4# b) 5#8#5#4# c) 5#8#15#14# d) 5#18#15#4#

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

8-What do you understand by the term Iteration?


Ans- Repeatation of statement/s finite number of times is known as Iteration

9- The output of the above code will be


for i in range(6):
if i ==3:
continue
print (i)
Ans-0 1 2 3 4 5

Bridge Course XII – Computer Science Page 20 of 60


Module – 5
Title – Programs on Loops

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

Bridge Course XII – Computer Science Page 21 of 60


Module – 6
Title – String Introduction

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

Concatenation Str1 + Str2

Repetition Str * x

Membership in , not in

Comparison str1 > str2

Slicing String[range]

STRING METHODS AND BUILT-IN FUNCTIONS:

FUNCTION DESCRIPTION

len() Returns the length of the string.


capitalize() Converts the first letter of the string in uppercase
It returns the string with first letter of every word in the string in uppercase and rest in
title()
lowercase.
lower() It converts the string into lowercase
upper() It converts the string into uppercase

WORKSHEET LEVEL - 1

1. Which of the following is the correct syntax of string slicing:


i. str_name[start:end] iii. str_name[start:step]
ii. str_name[step:end] iv. str_name[step:start]
2. What will be the output of the following code?
A=”Virtual Reality”
print(A.replace(‘Virtual’,’Augmented’))
i. Virtual Augmented iii. Reality Augmented
ii. Augmented Virtual iv. Augmented Reality
3. What will be the output of the following code?
print(“ComputerScience”.split(“er”,2))
i. *“Computer”,”Science”+ iii. *“Comput”,”Science”+
ii. *“Comput”,”erScience”+ iv. *“Comput”,”er”,”Science”+

Bridge Course XII – Computer Science Page 22 of 60


4. Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
i. he ii. lo iii. olleh iv. hello

5. ………..function will always return tuple of 3 elements.


i. index() ii. split() iii. partition() iv. strip()

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)

(i)If input will be str1= “Exam2021” then output will be


a. X***M202 b. X**M2021
c. x***m201 d. x***m202

(ii)If input will be str1= “CBSE-Exam” then output will be


a. Bs*-*x*** b. BS*-*x***
c. BS*-*x** d. BS**-*x**

(iii) If input will be str1= “PT1” then output will be


a. **T b. *T*
c. T** d. **

(iv) If input will be str1= “xyzA” then output will be


a. **A b. ***A
c. *xyz d. Error : String index out of range

9. What will be the output after the following statements?


x = 'Python'
y = 'y' in x
print(y)
a. [1] c. True
b. y d. False

Bridge Course XII – Computer Science Page 23 of 60


10. What will be the data type of x after the following statements?
false = "This is not true"
x = false
a. List c. Dictionary
b. String d. Boolean
11. What will be the output after the following statements?
x = 'hello'
for i in x:
print(i, end='')
a. h c. h e l l o
b. hello d. i x

WORKSHEET LEVEL - 2

1. What will be the output after the following statements?


x = 'Python'
y = 'MCQ'
print(x + y)
a. Python Python c. Python MCQ
b. MCQ MCQ d. PythonMCQ

2. What will be the output after the following statements?


x = 'Python '
print(x*3)
a. Pyt Pyt Pyt c. Python Python Python
b. t d. PythonPythonPython

3. What will be the output after the following statements?


x = 'Python '
print(x[4])
a. h c. Python Python Python Python
b. t d. o

4. What will be the output after the following statements?


x = 'Python'
print(x[2:4])
a. Pyth c. tho
b. th d. thon

5. What will be the output after the following statements?


x = 'Python'
print(x[:])
a. yth c. Python
b. Pn d. PythonPythonPython

6. What will be the output after the following statements?


x = 'Python'
print('y' in x)
a. y c. Python
b. Y d. True

Bridge Course XII – Computer Science Page 24 of 60


7. What will be the output after the following statements?
x = 'Python'
print('p' not in x)
a. p c. True
b. P d. False

8. What will be the output after the following statements?


x = 'Python'
print(x.capitalize())
a. Python c. PYTHON
b. Python.capitalize d. Python

9. What will be the output after the following statements?


x = 'python job interview'
print(x.title())
a. python job interview c. Python Job Interview
b. Python job interview d. Python job Interview

10. What will be the output after the following statements?


x = 'python jobs'
print(x.upper())
a. PYTHON JOBS c. Python Jobs
b. Python jobs d. python jobs

11. What will be the output after the following statements?


x = 'python jobs'
print(x.lower())
a. PYTHON JOBS c. Python Jobs
b. Python jobs d. python jobs

Bridge Course XII – Computer Science Page 25 of 60


Module – 7
Title – String Methods and Functions

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

1. What will be the output after the following statements?


x = 'Python Jobs'
print(x.swapcase())
a. PYTHON JOBS c. Python Jobs
b. pYTHON jOBS d. python jobs
2. What will be the output after the following statements?
x = 'Python'
print(x.join('33'))
a. Python33 c. Python3
b. 3Python3 d. Python 33
3. What will be the output after the following statements?
x = 'Python Test'
print(x.join('33'))
a
. 3Python Test3 c. Python3Test3
b. 3Python3Test d. Python Test33
4. What will be the output after the following statements?

Bridge Course XII – Computer Science Page 26 of 60


x = ' Python '
y = '3'
print(x.lstrip()+y.lstrip())
a. Python 3 c. Python3
b. 3Python3 d. Python+3
5. What will be the output after the following statements?
x = 'Python '
y = '3 '
print(x.rstrip()+y.rstrip())
a. Python 3 c. Python3
b. 3Python3 d. Python+3
6. What will be the output after the following statements?
x = ' Python '
y='3'
z = ' Questions '
print(x.strip()+y.strip()+z.strip())
a. Python 3 Questions c. Python3 Questions
b. Python3Questions d. Python 3Questions
7. What will be the output after the following statements?
x = 'Interview'
print(x.replace('e',' '))
a. Interview c. I n t e r v i e w
b. Intrviw d. Int rvi w
8. What will be the output after the following statements?
x = 'Python Pi Py Pip'
print(x.count('p'))
a. 1 c. 4
b. 0 d. 5
9. What will be the output after the following statements?
x = 'Python Pi Py'
print(x.find('p'))
a. -1 c. 1
b. 0 d. 3
10. What will be the output after the following statements?
x = 'Python Pi Py'

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

Bridge Course XII – Computer Science Page 27 of 60


c. True d. False
13. What will be the output after the following statements?
x = 'Python'
print(x.isalpha())

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

1. What will be the output after the following statements?


x = 'Python 3 MCQ'
print(x.isalnum())
a. 1 c. True
b. 0 d. False
2. What will be the output after the following statements?
x = 'Python 3 MCQ'
print(x.islower())
a. True c. 1
b. False d. 0
3. What will be the output after the following statements?
x = 'MCQ'
print(x.isupper())
a. True
b. False
c. 1
d. 0

4. What will be the output after the following statements?


x = '\n'
print(x.isspace())
a. True c. 1
b. False
d. 0

5. What will be the output after the following statements?


x = '2000'
print(x.isdigit())
a. True c. 1
b. False d. 0
6. What will be the output after the following statement?
print('2\\t4')
a. 2 t 4 c. 2 4
b. 2\t4 d. 2 tab 4
7. What will be the output after the following statements?

Bridge Course XII – Computer Science Page 28 of 60


a = 'Hello'
b = 'hello'
print(a is b)
a. a is b c. not b
b. False d. True
8. What will be the output after the following statements?
a = 'Python'
b = 'Python'
print(a is b)
a. a is b c. not b
b. False d. True

9. What type of error will be shown after the following statement?


a = 'Python' + 3
a. SyntaxError c. ValueError
b. TypeError d. NameError
10. In IDLE shell, which of the following statements gives SyntaxError?
a. "Python\tis\tEasy\n"
b. "Hello, it's very easy to learn Python"
c. "Python", "easy"
d. "Python is easy'

11. What is used for multi-line strings in Python?


a. Three braces {{{ }}} c. Three hashes ### ###
b. Three Colons ::: ::: d. Three Quotes ''' '''
12. What will be the output after the following statements?
x=''
print(x*5)
a. Displays a tab c. Displays a newline
b. Displays 5 spaces d. Displays 10 quotes
13. What will be the output after the following statements?
x = 'print("Python")'
eval(x)
a. x c. Python
b. print("Python") d. 0
14. What will be the output after the following statement?
a = "Python Practice'

a. SyntaxError c. ValueError
b. TypeError d. NameError

Module – 8
Title – Programs on Strings

WORKSHEET LEVEL - 1

Note: Programs to be done on computer preferably.

Bridge Course XII – Computer Science Page 29 of 60


1. Write code to create empty string ‘str’.
2. Write code to assign “Hello world” to a string variable ‘str2’.
3. Write a program to display each character of following string in separate line:
“Welcome to my world”
4. Write a program to count the length of string without using count function.
5. Write a program to accept strings and display total number of alphabets.

WORKSHEET LEVEL - 2

Note: Programs to be done on computer preferably.


1. Write code to assign “Hello world” to a string variable ‘str2’.
2. Write a program to display each character of following string in separate line:
“Welcome to my world”
3. Write a program to count the length of string without using count function.
4. Write a program to accept strings and display total number of alphabets.
5. Write a program to accept strings and display sum of digits if any present in
the string. If no digit is present then display 0.
6. Write a program to accept a string a convert it into lowercase.
7. Write a program to accept a sting and covert the cases of its each character.
i.e. change all lowercase letters to uppercase and vice-versa. For example: if
string is ‘ComPuter’ then output should be ‘cOMpUTER’.
8. Write a program to accept a string and display each word and it’s length.
9. Write a program to accept a string and replace all the word ‘do’ with ‘done’.
For example if entered string is “I do and do and we all will do” then output
should be “I done and done and we all will done”.

Page 30 of 60
Module – 9
Title – List Introduction

Introduction to Python List


The Python lists are containers that are used to store a list of values of any type. Python lists are mutable i.e.,
you can change the elements of a list in place. Which means Python will not create a fresh list when you make
changes to an element of a list. List is a type of sequence like strings and tuples.

Creating and Accessing Lists


The Lists are depicted through square brackets e.g., following are some lists in Python
*+
*1, 2, 3+
*1, 2.5, 3.7, 9+
*‘a’, ‘b’, ‘c’+
*‘a’, 1, ‘b’, 3.5, ‘zero’+
Creating Lists
To create a list put a number of expressions in square brackets. That is, use square brackets to indicate the start
and end of the list, and separate the items by commas. For example:
*2,4,6+
*‘abc’, ‘def’+
*1, 2.0, 3, 4.5+
*+
Thus to create a list you can write the code according to the syntax given below:
L = *value, …..+
This construct is known as list display construct. You can also create an empty list as:
L = list()
A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.
L1 = *3, 4, *5,6+, 7+
Creating Lists from existing sequences
You can also use the built-in list type object to create lists from sequences as per the syntax given below:
L = list(<sequence>)
where<sequence> can be any kind of sequence object You can use this method of creating lists of single characters
or single digits via keyboard input. Consider the code below
including strings, tuples and lists. Consider the following
L1 = list(input(“Enter list elements:”))
examples: Enter list elements: 234567
>>>L1 = list(‘Hello’) >>>L1
>>>L1 *‘2’,‘3’,‘4’,‘5’,‘6’,‘7’+
*‘H’, ‘e’, ‘l’, ‘l’, ‘o’+ Notice, this way the data type of all characters entered is
string. To enter a list of integers through keyboard, you can
>>>t = (‘w’, ‘e’, ‘r’, ‘t’, ‘y’) use the method given below:
>>>L2 = list(t) lst = eval(input(“Enter list to be added:”))
print (“list you entered:”,lst)
>>>L2
when you execute it, it will work somewhat like:
*‘w’, ‘e’, ‘r’, ‘t’, ‘y’+
Enter list to be added: *67, 78, 46, 23+
Accessing Lists list you entered: *67, 78, 46, 23+
Lists are sequences. They also index their individual
elements in two ways forward indexing as 0,1,2,3,….. and backward indexing as -1,-2,-3,……
List and strings are similar in following ways:
 Length: Function len(L) returns the number of items (count) in the list L.
 Indexing and Slicing: L*i+ returns the item at index i and L*i:j+ returns a new list containing objects at
indexes from i to j-1.
 Membership operators: Both ‘in’ and ‘not in’ operators work on Lists just like they work for other
sequences. That is, it tells if an element is present in the list or not and not in does for opposite.
Accessing Individual Elements

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

Working with Lists


Appending elements to a list

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

1. Why are lists called mutable types?


2. If a = *5,4,3,2,1,0+, evaluate the following expressions:
a. a*0+
b. a*-1+
c. a*a*0++
3. Is a string the same as a list of characters?
4. What does each of the following expression evaluate to?
L = *“These”, “are”, “a”, *“few”, “words”+, “that”, “we”, “will”, “use”+
a. L*3:4+
L*3:4+*0+
L*3:4+*0+*1+
L*3:4+*0+*1+*2+
b. “few” in L
c. “few” in L*3+
d. *L*1++ + L*3+
e. L*4:+
f. L*0:2+
5. What does a+b amounts to if a and b are lists?
6. What does a*b amounts to if a and b are lists?
7. What does a+b amounts to if a is a list and b = 5?
8. Which functions can you use to add elements to a list?
9. What is the difference between append() and insert() methods of list?
10. 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.

WORKSHEET LEVEL – 2

1. Why are lists called mutable types?


2. If a = *5,4,3,2,1,0+, evaluate the following expressions:
a. a*0+
b. a*-1+
c. a*a*0++
d. a*a*-1++
e. a*a*a*a*2++1+++
3. Is a string the same as a list of characters?
4. What are nested lists?
5. What does each of the following expression evaluate to?
L = *“These”, “are”, “a”, *“few”, “words”+, “that”, “we”, “will”, “use”+
a. L*3:4+
L*3:4+*0+
L*3:4+*0+*1+
L*3:4+*0+*1+*2+
b. “few” in L
c. “few” in L*3+

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

Q.1 Write a program to increment the elements of a list with a number?


Q. 2 Write a program that reverses a list of integers (in place)?
Q.3.Write a program that inputs two lists and creates a third, that contains all elements of the first
followed by all elements of the second?
Q.4. Write a program to accept a list of numbers and find the sum of all the numbers in the list and
add this total at the end of the list.
Q.5. Write a program to accept a list of numbers and replace all numbers greater than or equal to 33
with “PASS” and less than 33 with “FAIL” eg: if the accepted list is *23,45,56,29,90,33+, it should be
replaced as *“FAIL”,” PASS”,” PASS”,” FAIL”,” PASS”,” PASS”+.
Q.6. Write a program to accept elements of a list from the user . Multiply elements of the list with 7,
if an elements is a multiple of 7 otherwise multiply each element with 4. After processing, display the
elements.

WORKSHEET LEVEL – 2

Q.1 Write a program to increment the elements of a list with a number?


Q. 2 Write a program that reverses a list of integers (in place)?
Q.3.Write a program that inputs two lists and creates a third, that contains all elements of the first
followed by all elements of the second?
Q.4. Write a program to accept a list of numbers and find the sum of all the numbers in the list and
add this total at the end of the list.
Q.5. Write a program to accept a list of numbers and replace all numbers greater than or equal to 33
with “PASS” and less than 33 with “FAIL” eg: if the accepted list is *23,45,56,29,90,33+, it should be
replaced as *“FAIL”,” PASS”,” PASS”,” FAIL”,” PASS”,” PASS”+.
Q.6. Write a program to accept elements of a list from the user . Multiply elements of the list with 7,
if an elements is a multiple of 7 otherwise multiply each element with 4. After processing, display the
elements.
Q.7. W.A.P in python to ask the user to enter a list containing numbers between 1 and 12. Then
replace all of the entries in the list that are greater than 10 with 10.
Q.8. Write a program that takes any two lists L and M of the same size and adds their elements
together to form a new list N whose elements are sums of the corresponding elements in L and
M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4,6,13].
Q.9. Write a program to separate the character and numeric values from a list and store them in two
separate lists.
Q.10. Write a program to enter a list and a number. Subtract all elements of list from entered
number then remove all those elements which are 0 or below from the list. Print changed list,
number of elements in the list, number of elements removed from the list and sum of elements of
changed list.

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:

a) Empty Tuple : >>>T=()


b) Single element tuple: >>>t=(10,) # Must Place comma in single value tuple otherwise it will be
treated as a value, not a tuple.
c) Long tuple: >>>a=(5,10,15,20,25,30,35,40)
d) Nested Tuple: >>>b=(2,4,6,(8,10),12)
e) tuple() function is used to create a tuple from other sequences.

Comparing Tuples with lists:

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)

Common Tuple Operations:

Concatenation Tuple1 + Tuple2 >>>t1 = (3,5)


>>>t2 = (2,6,8,10)
>>>t1+t2
(3,5,2,6,8,10)
Repetition/ Replication Tuple * x >>> s = (2,4,6)

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)

Methods and functions:

Function/Method Description Example


len(tuple) Returns number of elements in given tuple. >>> t=(10,20,30,40,50)
>>>len(t)
5
tuple() Creates an empty tuple if no argument is passed >>> t1 = tuple()
>>> t2 = tuple([1,2,3,4]) #list
Creates a tuple if a sequence is passed as >>> t2
argument (1, 2, 3,4)
>>> t3 = tuple(range(5))
>>> t3
(0, 1, 2, 3, 4)
count (<item>) It will count and return number ofoccurrences of t=(10,20,30,40,50,60,70)
the passed element. >>> t.count(20)
1
>>> t.count(200)
0
index(<item>) Returns the index of the first occurrence of the >>> tuplel = (10,20,30,40,50)
element in given tuple >>> tuplel.index(30)
2
>>> tuple1.index(90)
ValueError
sorted() Takes elements in the tuple and returns a new >>> t1 = (10,100,50,60,30,40)
sorted list. It should be noted that, sorted() does >>> sorted(t1)
not make any change to the original tuple [10, 30, 40, 50, 60, 100]
min() Returns minimum or smallest element of the >>> t1 = (10,100,50,60,30,40)
tuple >>> min(t1)
10

max() Returns maximum or largest element of the tuple >>> t1 = (10,100,50,60,30,40)


>>> max(t1)
100
Returns sum of the elements of the Tuple >>> t1 = (10,100,50,60,30,40)
sum() >>> sum(t1)
290

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 :

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

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

4. ………function is used to convert a sequence data type into tuple.


i. List() ii tuple() iii TUPLE iv. tup()

5. ……….. function returns the number of elements in the tuple-


i. len( ) ii. max( ) iii. min( ) iv. count( )

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

Output Based Questions-


Consider the following tuples, tuple1 and tuple2:

tuple1 = (25, 10, 45, 67, 55, 9, 55, 45)


tuple2 = (10, 20)

Find the output of the following statements:

i. print(tuple1.index(9)) ii. print(tuple1.count(55))


iii. print(tuple1 + tuple2) iv. print(len(tuple2))
v. print(max(tuple1)) vi. print(min(tuple1))

Programs based on Tuples-


Q1. Write a python program to create tuple of 10 integer type elements and find the smallest and
largest elements in this tuple.

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

4. ………function is used to convert a sequence data type into tuple.


i. List() ii tuple() iii TUPLE iv. tup()

5. Elements in a tuple can be of ………….type.


i. Homogenous ii. Heterogenous iii. both i & ii iv. None of these

6. ……….. function returns the number of elements in the tuple-


i. len( ) ii. max( ) iii. min( ) iv. count( )

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

Output Based Questions-


Consider the following tuples, tuple1 and tuple2:

tuple1 = (25, 10, 45, 67, 55, 9, 55, 45)


tuple2 = (10, 20)

Find the output of the following statements:

i. print(tuple1.index(9)) ii. print(tuple1.count(55))


iii. print(tuple1 + tuple2) iv. print(len(tuple2))
v. print(max(tuple1)) vi. print(min(tuple1))
vii. print(sum(tuple2)) viii. print( sorted ( tuple1 ) )

Programs based on Tuples-


Q1. Write a python program to create tuple of 10 integer type elements and find the smallest and
largest elements in this tuple.
Q2. Write a program to input names of n students and store them in a tuple. Also, input a name from
the user and find if this student is present in the tuple or not.

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

Accessing items in a dictionary using keys: - Syntax: <dictionary-


The elements of dictionaries are accessed through the keys defined name>*<key>+
in the key: value pairs. Example: Dict*3+
Output: North
Accessing Keys and Values :
1. To see all the keys of a dictionary :
<dictionary_name>.keys() Example: Dict.keys()
2. To see all the values of a dictionary : Output: *1,2,3,4+
<dictionary_name>.values() Example: Dict.values()
3. To see all the items i.e. key value pairs together : Output: *‘East’,’West’,’North’,’South’+
<dictionary_name>.items() Example: Dict.items()
Output: *(1: 'East'), (2: 'West'),
(3:'North'), (4: ‘South’)+

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

2. Adding Dictionary elements:


We can add a new element (key : value pair) to a dictionary . The key being added should not
exist in the dictionary.
Syntax: <dictionary_name>*<new_key>+ = <new_value>
Example: Dict*5+=’North East’

3. Updating Dictionary elements:


We can modify an existing element (key : value pair) of a dictionary using the same method
as addition of new
element. Syntax: <dictionary_name>*<key>+ = <value>
Example: Dict*5+=’South East’

4. Deleting Dictionary elements:


There are two methods to delete elements from a dictionary: pop() function and del
keyword.

Using pop () method:


i) It takes <key> of the
Syntax: <dictionary_name>.pop(<key>)
Dictionary as a parameter and
Example: Dict.pop(5)
deletes the key:value pair
Output: South East
ii) It returns the deleted value

Using del keyword:


i) del keyword is used to free the
memory by deleting the item. Syntax: del <dictionary_name>*<key>+
ii) It does not return the deleted value Example: del Dict(1)
iii) If key is not provided, it will remove Output: ,2: 'West',3:'North', 4: ‘South’-
entire dictionary and throw Name Error.

Page 46 of 60
WORKSHEET LEVEL – 1

1. How is indexing of a dictionary different from that of a list or a string?


2. Which of the following types qualify to be the keys of a dictionary?
a. String
b. Tuple
c. Integer
d. Float
e. List
f. Dictionary
3. Why are dictionaries called mutable types?
4. How will you add key:value pairs to an existing dictionary?
5. Can you remove key:value pairs from a dictionary and if so, how?
6. Can sequence operations such as slicing and concatenation be applied to dictionaries? Why?

WORKSHEET LEVEL – 2

1. How is indexing of a dictionary different from that of a list or a string?


2. Which of the following types qualify to be the keys of a dictionary?
a. String
b. Tuple
c. Integer
d. Float
e. List
f. Dictionary
3. What do you mean by ordered collection and unordered collection? Give examples.
4. Give an example where dictionaries are more useful than lists.
5. Why are dictionaries called mutable types?
6. What are different ways of creating dictionary?
7. How will you add key:value pairs to an existing dictionary?
8. Can you remove key:value pairs from a dictionary and if so, how?
9. Can sequence operations such as slicing and concatenation be applied to dictionaries? Why?
10. If the addition of a new key:value pair causes the size of the dictionary to grow beyond its original size,
an error occurs. True or False?

Page 47 of 60
Module – 14
Title – Dictionary – Methods, functions and programs
Dictionary methods and functions:

SNo FUNCTIONS DESCRIPTION EXAMPLE


1 len( ) Returns the length of the Mydict={1: 'East', 2: 'West'}
Dictionary (key-value pair will Syntax: len(<dict>)
be count as 1 ) Example: len(Mydict)
Output: 2

2 get( ) This method returns the value Syntax: <dict>.get(<key>)


associated with the key Example: Mydict.get(2)
provided in the get method. Output: ‘West’

3 update() This method updates the Syntax: <dict>.update(<dict2>)


dictionary with the elements Example: mydict.update({3:’North’)
from another dictionary object.

4 popitem() It removes and returns a (key, Syntax: <dict>.popitem()


value) pair as tuple. Example: mydict. popitem()
Pairs are returned in LIFO (last- Output: 3:’North’
in, first-out) order.

5 fromkeys() The dict.fromkeys() method Syntax:


creates a new dictionary from <dict>.fromkeys(<keys>,<value>)
the given iterable (string, list, Example:
set, tuple) as keys and with the d = dict.fromkeys([1,2,3], 10)
specified value. Output:
{1:10,2:10,3:10}
6 copy( ) copy() method returns a copy Syntax: <dict>.copy()
(shallow copy) of the original Example:
dictionary Mydict={1: 'East', 2: 'West'}
D=Mydict.copy()
Output:
{1: 'East', 2: 'West'}
7 setdefault( ) The setdefault() method Syntax:
returns the value of a key (if <dict>.setdefault(<key>,<default>)
the key is in Example: d1.setdefault(4, ‘South’)
dictionary). If not, it inserts key Output: South
with a value to the dictionary. Example: d1.setdefault(1, ‘North’)
Output: East

8 max( ) It is Used to find maximum Syntax: max(<dict>)


value from the dictionary. Example: D1= {1:10, 2:20, 3:30}

Page 48 of 60
max(D1)
Output: 3

9 min( ) It is used to find minimum value Syntax: min(<dict>)


from the dictionary. Example: D1= {1:10, 2:20, 3:30}
min(D1)
Output: 1

10 clear() This method removes all items Syntax: <dict>.clear()


from the dictionary and the Example: Mydict.clear()
dictionary becomes empty. Output: { }

11 sorted( ) This method returns the sorted Syntax: sorted(<dict>)


list of keys from the dictionary Example: D1= {5:10, 1:20, 3:30}
Sorted(d1)
Output: [1,3,5]

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)

2. A dictionary D1 has values in the form of lists of numbers. Write a program to


create a new dictionary D2 having same keys as D1 but values as the sum of the list
elements
e.g., D1 = ,'A' : *1, 2, 3+ , 'B' : *4, 5, 6+- then D2 is ,'A' :6, 'B' : 15-

D1 = eval(input("Enter a dictionary D1: "))


print("D1 =", D1)

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

5. Write a Python code to check if a dictionary contains a key-value pair.

d = ,"a": 1, "b": 2, "c": 3-


key = input(“Enter key”)
value = int(input(“Enter Value”))
if key in d.keys() and value in d.values():
print(“Contains Key Value Pair”)
else:
print(“Does not contain Key Value Pair”)
======================================

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

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.
3. Marks of three students “Suniti”, “Ryna” and “Zeba” in three subjects are available in following three
dictionaries respectively:
d1 = ,1:40, 2:70, 3:70-
d2 = ,1:40, 2:50, 3:60-
d3 = ,1:70, 2:80, 3:90-
Create a nested dictionary that stores the marks details along with student names and hten prints the
output as shown below:

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

We can import a library by using keyword import and from

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

import < module_name> as <alias_name>

math module

Frequently
used Constants
sqrt() functions in abs()
math module pi

ceil() fabs() e

math.pi

pow() floor() math.e

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() Returns the absolute value of x

>>> import math

>>> math.fabs(-5.5)

5.5

Python- random module

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

1. Generating random floats:


For this purpose we use random() function. It will generate any float value between 0 and 1.
import random
x=random.random() # here x is a float value , 0<x<1
2. Generating random integers:
Random integers can be generated with help of following two functions
i) random.randint(a,b)
It will generate an integer between a and b including a and b

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

statistics module: used to calculate mathematical statistics of numeric data


Method Description

statistics.mean() Calculates average of the given data

statistics.median() Calculates the middle value of the data

statistics.mode() Calculates the mode( central tendency) of the numeric data

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

1 What is a Python module?


a) A built-in function
b) A collection of Python functions and global variables
c) A type of Python data structure
d) A programming language
2 Which keyword is used to import a module in Python?
a) use
b) require
c) import
d) include
3 Which keyword is used to create an alias while importing a module in Python?
a) as b) alias
c) rename d) with
4 The purpose of the ‘math’ module in Python is
a) To handle file I/O operations
b) To perform mathematical operations
c) To interact with the operating system
d) To manipulate strings
5 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
6 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
7 The output of the following Python code is either 1 or 2.
import random
random.randint(1,2)
a) True b) False
8 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)
9 What will be the output of the following Python code?
random.randrange(0,91,5)
a) 10
b) 18
c) 79
d) 95
10 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=’@’)

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

1 What is a Python module?


a) A built-in function
b) A collection of Python functions and global variables
c) A type of Python data structure
d) A programming language
2 Which keyword is used to import a module in Python?
a) use
b) require
c) import
d) include
3 Which of the following statements is true about packages in Python?
a) Packages are collections of modules
b) Packages are collections of functions
c) Packages are used for mathematical operations
d) Packages are used for string manipulation
4 Which keyword is used to create an alias while importing a module in Python?
a) as b) alias
c) rename d) with
5 The purpose of the ‘math’ module in Python is
a) To handle file I/O operations
b) To perform mathematical operations

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

You might also like