Python Revision Tour I and II Notes
Python Revision Tour I and II Notes
name
XII-CSC LESSON NOTES-PYTHON REVISION TOUR I 2. break
3. section
4. mark12
Multiple Choice Questions
Answer
Question 1
break
Which of the following is an invalid variable?
Reason — break is a reserved keyword.
1. my_day_2
2. 2nd_day Question 3
Question 2
eval
Find the invalid identifier from the following: Reason — eval is not a keyword in python.
1
Question 4 Class
Which of the following cannot be a variable? Reason — Class is not a core data type.
1. _init_ Question 6
2. in
3. it How would you write xy in Python as an
expression ?
4. on
1. x^y
Answer
2. x**y
in 3. x^^y
4. none of these
Reason — in is a keyword in python.
Answer
Question 5
x**y
Which of these is not a core data type?
Reason — ** is an arithmetic operator used for
1. Lists
exponentiation.
2. Dictionary
3. Tuples Question 7
4. Class
What will be the value of the expression?
Answer 14 + 13 % 15
2
1. 14 3. 1.0
2. 27 4. 1
3. 12
Answer
4. 0
0
Answer
Reason — According to operator precedence,
27
floor division (//) and remainder (%) both have
Reason — According to operator precedence equal precedence hence the expression will be
remainder (%) operation will be done first and evaluated from left to right.
then addition (+) will be done.
A % B // A
14 + 13 % 15 = 16 % 15 // 16
= 14 + 13 = 1 // 16
= 27 =0
Question 8 Question 9
print("hello\\example\\test.txt")
1. float('12')
2. int('12') Reason — Escape sequence (\\) is used for
3. float('12.5') Backslash (\).
4. int('12.5')
Question 14
Answer
Which value type does input() return ?
int('12.5')
1. Boolean
Reason — int() are positive or negative whole 2. String
numbers with no decimal point. 3. Int
4. Float
Question 13
1. print("hello\example\test.txt")
5
Reason — The input() function always returns a Select all of the function calls that result in this
value of String type. output
Question 15 1. print('''Eina
\nMina
Which two operators can be used on numeric \nDika''')
values in Python? 2. print('''EinaMinaDika''')
1. @ 3. print('Eina\nMina\nDika')
2. % 4. print('Eina
3. + Mina
4. # Dika')
Answer Answer
%, + print('Eina\nMina\nDika')
1. print('''Eina
Question 16
\nMina
Which of the following four code fragments will \nDika''') — It is a multiline string and by
yield following output? adding \n extra line will be added.
Eina
2. print('''EinaMinaDika''') — There is no new
Mina line character.
Dika
6
3. print('Eina\nMina\nDika') — It adds new For a given declaration in Python as s =
line by \n new line character. "WELCOME", which of the following will be the
4. print('Eina correct output of print(s[1::2])?
Mina
1. WEL
Dika') — It creates an error because it is a
2. COME
multiline string with no triple quotes.
3. WLOE
Question 17 4. ECM
in Question 2
Question 20 Question 3
Which of the following is not a Tuple in Python? A keyword is a word having special meaning and
role as specified by programming language.
1. (1,2,3)
2. ("One","Two","Three") Question 4
3. (10,)
The data types whose values cannot be changed
4. ("One") in place are called immutable types.
Answer Question 5
8
compiler without programmer's intervention, it Python's keywords cannot be used as variable
is called implicit type conversion. name.
Question 10
True
9
Reason — Parentheses has first precedence 4/(3*(4-2))
then multiplication then division has = 4/(3*2)
precedence. = 4/6
= 0.6666
4/(3*(2-1))
= 4/(3*1) 4/3*(4-2)
= 4/3 = 4/3*2
= 1.33333 = 1.3333*2
= 2.6666
4/3*(2-1)
= 4/3*1 Question 4
= 4/3
= 1.33333 The expression 2**2**3 is evaluated as:
(2**2)**3.
Question 3
Answer
The value of the expressions 4/(3*(4 - 2)) and
False
4/3*(4 - 2) is the same.
Reason — The expression 2**2**3 is evaluated
Answer
as: 2**(2**3) because exponentiation operates
False from right to left (i.e., it is right associative).
Answer
Question 6
False
Variables can be assigned only once.
Reason — Loops in Python can have else clause
Answer
too.
False
Question 9
Reason — Python supports dynamic typing i.e.,
a variable can hold values of different types at Python loops can also have else clause.
different times. Answer
Question 7 True
In Python, a variable is a placeholder for data.
11
Reason — Loops in Python can have else clause. (a)
12
Reason. Triple Quotation marks are not valid in Assertion is false but Reason is true.
Python.
Explanation
Answer if is conditional statement and for is loop
statement. Python is case sensitive and its
(c)
selection and looping statements are in lower
Assertion is true but Reason is false. case.
Explanation Question 4
A string literal is a sequence of characters
Assertion. if and for are legal statements in
surrounded by single or double or triple single
Python.
quotes or triple double quotes.
Reason. Python is case sensitive and its basic
Question 3
selection and looping statements are in lower
Assertion. If and For are legal statements in case.
Python.
Answer
Reason. Python is case sensitive and its basic
(a)
selection and looping statements are in lower
case. Both Assertion and Reason are true and Reason
is the correct explanation of Assertion.
Answer
Explanation
(d)
if is conditional statement and for is loop
13
statement. Python is case sensitive and its Assertion. The break statement can be used
selection and looping statements are in lower with all selection and iteration statements.
case.
Reason. Using break with an if statement will
Question 5 give no error.
Price*Qty Answer
class
16
The invalid identifier are: 1. ?
2. <
2ndName ⇒ Begins with a digit
3. **
True ⇒ It is a keyword
4. and
Question 7
Answer
Which of the following is an invalid datatype in
Python ? **
18
8. in a = 15
b = a - 10
Answers
Question 14
The valid operators are:
What all components can a Python program
** ⇒ Exponentiation operator
contain?
is ⇒ Identity operator
^ ⇒ Bitwise XOR operator Answer
in ⇒ Membership operator
A Python program can contain various
Question 13 components like expressions, statements,
comments, functions, blocks and indentation.
What is an expression and a statement?
Question 15
Answer
What are variables? How are they important for
An expression is any legal combination of
a program?
symbols that represents a value. For example,
2.9, a + 5, (3 + 5) / 4. Answer
A statement is a programming instruction that
does something i.e. some action takes place. For Variables are named labels whose values can be
example: used and processed during program run.
print("Hello") Variables are important for a program because
they enable a program to process different sets
of data.
19
Question 16 Question 17
Consider the given expression: not True and Describe the concepts of block and body. What is
False or True indentation and how is it related to block and
body?
Which of the following will be correct output if
the given expression is evaluated? Answer
Reason — The 'not' operator has the highest What are data types? How are they important?
precedence, followed by 'and', which has
Answer
precedence over 'or', and the evaluation
proceeds from left to right. Data types are used to identify the type of data a
not True and False or True memory location can hold and the associated
= False and False or True operations of handling it. The data that we deal
= False or True with in our programs can be of many types like
= True character, integer, real number, string, boolean,
20
etc. hence programming languages including How many integer types are supported by
Python provide ways and facilities to handle all Python? Name them.
these different types of data through data types.
Answer
The data types define the capabilities to handle a
specific type of data such as memory space it Two integer types are supported by Python. They
allocates to hold a certain type of data and the are:
range of values supported for a given data type,
etc. 1. Integers (signed)
2. Booleans
Question 18(b)
Question 20
Write the names of any four data types available
in Python. What are immutable and mutable types? List
immutable and mutable types of Python.
Answer
Answer
The names of any four data types in Python are:
Mutable types are those whose values can be
1. Integer changed in place whereas Immutable types are
2. String those that can never change their value in place.
3. List
Mutable types in Python are:
4. Tuple
1. Lists
Question 19
2. Dictionaries
21
3. Sets Implicit Type Conversion
Immutable types in Python are:
programmer's intervention.
1. Integers
2. Floating-Point numbers Example:
3. Booleans a, b = 5, 25.5
4. Strings c=a+b
5. Tuples
Question 22
Question 21
An immutable data type is one that cannot
What is the difference between implicit type
change after being created. Give three reasons
conversion and explicit type conversion?
to use immutable data.
Answer
Answer
Implicit Type Conversion Three reasons to use immutable data types are:
An implicit type conversion is automatically performed 1. Immutable data types increase the
by the compiler when differing data types are efficiency of the program as they are
intermixed in an expression. quicker to access than mutable data types.
2. Immutable data types helps in efficient use
An implicit type conversion is performed without of memory storage as different variables
22
containing the same value can point to the Answer
same memory location. Immutability
The pass statement of Python is a do nothing
guarantees that contents of the memory
statement i.e. empty statement or null operation
location will not change.
statement. It is useful in scenarios where syntax
3. Immutable data types are thread-safe so
of the language requires the presence of a
they make it easier to parallelize the
statement but the logic of the program does not.
program through multi-threading.
For example,
Question 23 for i in range(10):
if i == 2:
What is entry controlled loop? Which loop is pass
else:
entry controlled loop in Python? print("i =", i)
Answer
Question 25
An entry-controlled loop checks the condition at
Rewrite the adjacent code in python after
the time of entry. Only if the condition is true,
removing all syntax error(s). Underline each
the program control enters the body of the loop.
correction done in the code.
In Python, for and while loops are entry-
controlled loops. 30 = To
for K in range(0,To)
IF k%4 == 0:
Question 24 print(K * 4)
Else:
Explain the use of the pass statement. Illustrate print(K+3).
it with an example.
23
Answer Below are seven segments of code, each with a
part coloured. Indicate the data type of each
The corrected code is shown below:
coloured part by choosing the correct type of
To = 30 # Correction 1 data from the following type.
for K in range(0,To): # Correction 2
if K % 4 == 0: # Correction 3 (a) int
print(K * 4)
else: # Correction 4 (b) float
print(K+3) # Correction 5 (c) bool
Explanation (d) str
(e) function
Correction 1 — Variable should be on left side (f) list of int
and literals should be on right side. (g) list of str
Correction 2 — Semi-colon was missing in the for
loop syntax. (i)
Correction 3 — if statement should be in lower if temp < 32 :
case. print ("Freezing")
Correction 4 — else statement should be in (ii)
lower case.
L = ['Hiya', 'Zoya', 'Preet']
Correction 5 — Full stop should not be there at print(L[1])
the end of print function.
(iii)
Question 26 M = []
for i in range (3) :
M.append(i)
24
print(M) (v) bool
(iv) (vi) list of str
(vii) str
L = ['Hiya', 'Zoya', 'Preet']
n = len(L)
if 'Donald' in L[1 : n] : Question 27
print(L)
Write the output of the following Python code:
(v)
for i in range(2,7,2):
if n % 2 == 0 : print(i*'$')
print("Freezing")
Answer
(vi)
L = inputline.split() Output
while L != ( ) :
print(L) $$
L = L[1 :] $$$$
$$$$$$
(vii)
Explanation
L = ['Hiya', 'Zoya', 'Preet']
print(L[0] + L[1])
range(2,7,2) returns [2, 4, 6] as it defines a range
Answer of 2 to 6 with a step of 2. The loop iterates as
below:
(i) bool
(ii) str For i = 2, it prints $$.
(iii) list of int For i = 4, it prints $$$$.
(iv) int
25
For i = 6, it prints $$$$$$. Answer
#Read the limit
Type B: Application Based Questions limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
Question 1 next_price = float(input("Enter a price or 0 to
stop:"))
Fill in the missing lines of code in the following while next_price > 0 :
code. The code reads in a limit amount and a list if next_price < limit and next_price >
max_price:
of prices and prints the largest price that is less max_price = next_price
than the limit. You can assume that all prices #Read the next price
next_price = float(input("Enter a price or 0
and the limit are positive numbers. When a price
to stop:"))
0 is entered the program terminates and prints if max_price > 0:
the largest price that is less than the limit. print("Largest Price =", max_price)
else :
#Read the limit print("Prices exceed limit of", limit);
limit = float(input("Enter the limit"))
max_price = 0 Question 2a
# Read the next price
next_price = float(input("Enter a price or 0 to Predict the output of the following code
stop:"))
while next_price > 0 : fragments:
<write your code here>
#Read the next price count = 0
<write your code here> while count < 10:
if max_price > 0: print ("Hello")
<write your code here> count += 1
else :
<write your code here> Answer
26
Output 8 2
7 3
Hello 6 4
Hello
Hello Explanation
Hello
Hello
Hello x y Output
Hello
Hello
Hello 10 0 10 0
Hello
10 0
Question 2b 9 1
91
Predict the output of the following code
fragments: 10 0
x = 10 8 2 91
y = 0 82
while x > y:
print (x, y)
x = x - 1 10 0
y = y + 1
91
7 3
Answer 82
73
Output
10 0 6 4 10 0
9 1
27
70
x y Output 60
50
91
Explanation
82
73 Inside while loop, the line x = x - 10 is
64 decreasing x by 10 so after 5 iterations of while
loop x will become 40. When x becomes 40, the
condition if x < 50 becomes true so keepgoing is
Question 2c
set to False due to which the while loop stops
Predict the output of the following code iterating.
fragments:
Question 2d
keepgoing = True
x=100 Predict the output of the following code
while keepgoing :
print (x) fragments:
x = x - 10
if x < 50 : x = 45
keepgoing = False while x < 50 :
print (x)
Answer
Answer
Output This is an endless (infinite) loop that will keep
100 printing 45 continuously.
90
80
28
As the loop control variable x is not updated Question 2f
inside the loop neither there is any break
Predict the output of the following code
statement inside the loop so it becomes an
fragments:
infinite loop.
for p in range(1,10):
Question 2e print (p)
Answer
Predict the output of the following code
fragments: Output
for x in [1,2,3,4,5]:
1
print (x)
2
3
Answer
4
5
Output 6
7
1 8
2 9
3
4
5 Explanation
29
Question 2g this sequence is assigned to z one by one and
then z gets printed inside the for loop.
Predict the output of the following code
fragments: Question 2h
for z in range(-500, 500, 100):
print (z) Predict the output of the following code
fragments:
Answer
x = 10
Output y = 5
for i in range(x-y * 2):
-500 print (" % ", i)
-400
-300 Answer
-200
-100 This code generates No Output.
0
100
Explanation
200
300
400 The x-y * 2 in range(x-y * 2) is evaluated as
below:
Explanation x-y*2
⇒ 10 - 5 * 2
generates a sequence of
range(-500, 500, 100)
⇒ 10 - 10 [∵ * has higher precedence than -]
numbers from -500 to 400 with each subsequent
⇒0
number incrementing by 100. Each number of
30
Thus range(x-y * 2) is equivalent times. c is incremented by 1 in each execution so
to range(0) which returns an empty sequence — [ final value of c becomes 50.
].
Question 2j
Question 2i
Predict the output of the following code
Predict the output of the following code fragments:
fragments:
x = [1,2,3]
c = 0 counter = 0
for x in range(10): while counter < len(x):
for y in range(5): print(x[counter] * '%')
c += 1 for y in x:
print (c) print(y * '* ')
counter += 1
Answer
Answer
Output
Output
50
%
*
Explanation * *
* * *
Outer loop executes 10 times. For each iteration %%
*
of outer loop, inner loop executes 5 times. Thus, * *
the statement c += 1 is executed 10 * 5 = 50 * * *
%%%
*
31
* * Explanation
* * *
The for loop extracts each letter of the string
Explanation 'lamp' one by one and place it in variable x.
In this code, the for loop is nested inside the Inside the loop, x is converted to uppercase and
while loop. Outer while loop runs 3 times and printed.
prints % as per the elements in x in each
Question 2l
iteration. For each iteration of while loop, the
inner for loop executes 3 times printing * as per Predict the output of the following code
the elements in x. fragments:
x = 'one'
Question 2k
y = 'two'
counter = 0
Predict the output of the following code while counter < len(x):
fragments: print(x[counter], y[counter])
counter += 1
for x in 'lamp':
print(str.upper(x)) Answer
Answer Output
Output o t
n w
L e o
A
M Explanation
P
32
Inside the while loop, each letter of x and y is Question 2n
accessed one by one and printed.
Predict the output of the following code
Question 2m
fragments:
x ='apple, pear, peach, grapefruit'
Predict the output of the following code y = x.split(', ')
fragments: for z in y:
if z < 'm':
x = "apple, pear, peach" print(str.lower(z))
y = x.split(", ") else:
for z in y : print(str.upper(z))
print(z)
Answer
Answer
Output
Output
apple
apple PEAR
pear PEACH
peach grapefruit
Explanation Explanation
x.split(", ") breaks up string x into a list of strings x.split(', ') breaks up string x into a list of strings
so y becomes ['apple', 'pear', 'peach']. The for so y becomes ['apple', 'pear', 'peach',
loop iterates over this list and prints each string 'grapefruit']. The for loop iterates over this list.
one by one. apple and grapefruit are less than m (since a and
g comes before m) so they are converted to
33
lowercase and printed whereas pear and peach 5 + 3 ** 2 / 2
are converted to uppercase and printed. =5+9/2
= 5 + 4.5
Question 3 = 9.5
Which of the following is the correct output for
Question 4(i)
the execution of the following Python
statement ? How many times will the following for loop
execute and what's the output?
print(5 + 3 ** 2 / 2)
for i in range(-1, 7, -2):
1. 32 for j in range (3):
2. 8.0 print(1, j)
3. 9.5 Answer
4. 32.0
The loops execute 0 times and the code
Answer produces no output. range(-1, 7, -2) returns an
empty sequence as there are no numbers that
9.5 start at -1 and go till 6 decrementing by -2. Due
to empty sequence, the loops don't execute.
Explanation
Question 4(ii)
According to operator precedence,
exponentiation(**) will come first then division How many times will the following for loop
then addition. execute and what's the output?
34
for i in range(1,3,1): Find and write the output of the following
for j in range(i+1):
print('*') python code:
35
that terminates the loop. Outside the loop, Got ⇒ n = 2n - n + 1
it! gets printed. ⇒n=n+1
n=2*n-m Solution
n = 2 * n - (n - 1) if x < 0:
print("negative")
⇒n=2*n-n+1 elif x > 0:
print("positive")
36
else: Enter a number: 10
print("zero") True
Enter a number: 5
Output
False
Enter x: -5
negative Question 3
37
saying if first number is divisible by second Tuesday etc. Then the program should display
number or if it is not. the day on the day-number that has been input.
Solution Solution
Question 5
Output
Write a program that asks the user the day Enter day number: 243
number in a year in the range 2 to 365 and asks First day of year: FRIDAY
Day on day number 243 : TUESDAY
the first day of the year — Sunday or Monday or
38
Question 6 displayLength(inchLen)
n = int(input("Enter N: "))
def getInput():
sum = 0
len = int(input("Enter length in feet: "))
if n < 0:
return len
for i in range(2 * n, n + 1):
sum += i
def displayLength(l):
else:
print("Length in inches =", l)
for i in range(n, 2 * n + 1):
sum += i
ipLen = getInput()
inchLen = feetToInches(ipLen)
39
print("Sum =", sum) monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
Output
year = dateStr[4:]
Enter N: 5
Sum = 45 newDateStr = month + ' ' + day + ', ' + year
print(newDateStr)
Enter N: -5
Sum = -45 Output
41
# the time duration between the two times The numbered position of a letter in a string is
diff = sMins - fMins;
called ...............
# Convert the difference to hours & mins
hrs = diff // 60 1. position
mins = diff % 60
2. integer position
print(hrs, "hours", mins, "minutes") 3. index
4. location
Output
Question 2
1. exists
Multiple Choice Questions 2. in
3. into
Question 1 4. inside
42
Answer Following set of commands is executed in shell,
what will be the output?
in
>>>str = "hello"
Reason — in is membership operator which >>>str[:2]
>>>
returns True if a character or a substring exists
in the given string else returns False. 1. he
2. lo
Question 3
3. olleh
The keys of a dictionary must be of ............... 4. hello
types.
Answer
1. integer
2. mutable he
3. immutable Reason — str[:2] here slicing operation begins
4. any of these from index 0 and ends at index 1. Hence the
output will be 'he'.
Answer
Question 5
immutable
What data type is the object below ?
Reason — Dictionaries are indexed by keys and
L = [1, 23, 'hello', 1]
its keys must be of any immutable type.
1. list
Question 4
43
2. dictionary Reason — For creating a tuple, enclosing the
3. array elements inside parentheses is optional. Even if
4. tuple parentheses are omitted as shown here, still this
statement will create a tuple.
Answer
Question 7
list
To store values in terms of key and value, what
Reason — A list can store a sequence of values core data type does Python provide ?
belonging to any data type and they are depicted
through square brackets. 1. list
2. tuple
Question 6 3. class
What data type is the object below ? 4. dictionary
L = 1, 23, 'hello', 1
Answer
1. list
dictionary
2. dictionary
3. array Reason — Dictionaries are mutable with
4. tuple elements in the form of a key:value pair that
associate keys to values.
Answer
Question 8
tuple
44
What is the value of the following expression ? 1. del AL[2]
3 + 3.00, 3**3.0 2. AL[2:3] = []
3. AL[2:2] = []
1. (6.0, 27.0)
4. AL[2] = []
2. (6.0, 9.00)
5. AL.remove(3)
3. (6, 27)
4. [6.0, 27.0] Answer
5. [6, 27]
del AL[2]
Answer AL[2:3] = []
AL.remove(3)
(6.0, 27.0)
Reason — del AL[2] — The del keyword deletes
Reason — The value of expression is in round the element from the list AL from index 2.
brackets because it is tuple. AL[2:3] = [] — The slicing of the list AL[2:3] begins at
3 + 3.00 = 6.0 index 2 and ends at index 2. Therefore, the
3**3.0 = 3 x 3 x 3 = 27.0 element at index 2 will be replaced by an empty
list [].
Question 9
AL.remove(3) — The remove() function removes an
List AL is defined as follows : AL = [1, 2, 3, 4, 5] element from the list AL from index 3."
Which of the following statements removes the
middle element 3 from it so that the list AL Question 10
equals [1, 2, 4, 5] ?
45
Which two lines of code are valid strings in 2. work
Python ? 3. mywork
4. my
1. This is a string
2. 'This is a string' Answer
3. (This is a string)
4. "This is a string" Output
mywork
Answer
Reason — The + operator creates a new string
'This is a string' by joining the two operand strings.
"This is a string"
Question 12
Reason — Strings are enclosed within single or
You have the following code segment :
double quotes.
String1 = "my"
Question 11 String2 = "work"
print(String1+String2.upper())
You have the following code segment : What is the output of this code?
String1 = "my"
String2 = "work" 1. mywork
print(String1 + String2) 2. MY Work
What is the output of this code? 3. myWORK
4. My Work
1. my work
46
Answer type (for addition) or of string type (for
concatenation). It cannot work with one operand
Output as string and one as a number.
myWORK
Question 14
Reason — string.upper() method returns a copy
of the string converted to uppercase. The + What is the output of this code ?
operator creates a new string by joining the two
>>> int("3" + "4")
operand strings.
1. "7"
Question 13
2. "34"
Which line of code produces an error ? 3. 34
4. 24
1. "one" + 'two'
2. 1 + 2 Answer
3. "one" + "2"
4. '1' + 2 Output
34
Answer Reason — The + operator concatenates two
'1' + 2 strings and int converts it to integer type.
int("3" + "4")
Reason — The + operator has to have both = int("34")
operands of the same type either of number = 34
47
Question 15 1. Day = {1:'Monday', 2:'Tuesday',
3:'wednesday'}
Which line of code will cause an error ?
2. Day = {1;'Monday', 2;'Tuesday',
1. num= [5, 4, 3, [2], 1] 3;'wednesday'}
2. print(num[0])
3. print(num[3][0]) 3. Day = [1:'Monday', 2:'Tuesday',
4. print(num[5]) 3:'wednesday']
1. Line 3 4. Day = {1'monday', 2'tuesday',
2. Line 2 3'wednesday'}
3. Line 4 Answer
4. Line 1
Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'}
Answer
Reason — The syntax of dictionary declaration
Line 4 is:
has 5 elements which counts to index 4. According this syntax, Day = {1:'Monday',
2:'Tuesday', 3:'wednesday'} is the correct answer.
Question 16
Question 17
Which is the correct form of declaration of
dictionary ? Identify the valid declaration of L:
L = ['Mon', '23', 'hello', '60.5']
48
1. dictionary T[2] = -29
2. string
Reason — Tuples are immutable. Hence we
3. tuple
cannot perform item-assignment in tuples.
4. list
Fill in the Blanks
Answer
list Question 1
Reason — A list can store a sequence of values Strings in Python store their individual letters in
belonging to any data type and enclosed in Memory in contiguous location.
square brackets.
Question 2
50
The items() function returns all the Key : value False
pairs as (key, value) sequences.
Reason — A list can store any data types and
True/False Questions even list can contain another list as element.
Question 3
Question 1
There is no conceptual limit to the size of a list.
Do both the following represent the same list.
['a', 'b', 'c'] Answer
['c', 'a', 'b']
True
Answer
Reason — The list can be of any size.
False
Question 4
Reason — Lists are ordered sequences. In the
above two lists, even though the elements are All elements in a list must be of the same type.
same, they are at different indexes (i.e., different
Answer
order). Hence, they are two different lists.
False
Question 2
Reason — A list is a standard data type of
A list may contain any type of objects except python that can store a sequence of values
another list. belonging to any data type.
Answer
51
Question 5 Answer
A given object may appear in a list more than False
once.
Reason — The + operator has to have both
Answer operands of the same type either of number
type (for addition) or both of string type (for
True
concatenation). It cannot work with one operand
Reason — List can have duplicate values. as string and one as a number.
Question 6 Question 8
The keys of a dictionary must be of immutable The clear( ) removes all the elements of a
types. dictionary but does not delete the empty
dictionary.
Answer
Answer
True
True
Reason — Dictionaries are indexed by keys.
Hence its keys must be of any non-mutable type. Reason — The clear() method removes all items
from the dictionary and the dictionary becomes
Question 7 empty dictionary post this method. del
statement removes the complete dictionary as
You can combine a numeric value and a string by
an object.
using the + symbol.
52
Question 9 differ from strings, such as append(), extend(),
pop() etc.
The max( ) and min( ) when used with tuples, can
work if elements of the tuple are all of the same Question 11
type.
For any index n, s[:n] + s[n:] will give you original
Answer string s.
True Answer
Reason — Tuples should contain same type of True
elements for max() and min() method to work.
Reason — s[:n] — The slicing of a string starts
Question 10 from index 0 and ends at index n-1.
s[n:] — The slicing of a string starts from index n
A list of characters is similar to a string type.
and continues until the end of the string.
Answer So when we concatenate these two substrings
we get original string s.
False
Question 12
Reason — In Python, a list of characters and a
string type are not similar. Strings are immutable A dictionary can contain keys of any valid Python
sequences of characters, while lists are mutable types.
sequences that can contain various data types.
Lists have specific methods and behaviors that Answer
53
False used to store collections of items, but they have
different properties and use cases. Lists are
Reason — The keys of a dictionary must be of
mutable, meaning you can add, remove, or
immutable types.
modify elements after the list is created. Tuples,
on the other hand, are immutable, meaning
Assertions and Reasons
once a tuple is created, its contents cannot be
changed.
Question 1
types of Python, yet they are two different data Assertion. Modifying a string creates another
types. string internally but modifying a list does not
Reason. List sequences are mutable and Tuple create a new list.
sequences are immutable. Reason. Strings store characters while lists can
Answer store any type of data.
(a) Answer
(d) (a)
Assertion is false but Reason is true. Both Assertion and Reason are true and Reason
is the correct explanation of Assertion.
Explanation
Dictionaries are indexed by keys and each key Explanation
must be immutable and unique. However, the A dictionary is a unordered set of key : value
dictionary itself is mutable, meaning that we can pairs and are indexed by keys. The values of a
add, remove, or modify key-value pairs within dictionary can change but keys of dictionary
the dictionary without changing the identity of cannot be changed because through them data
the dictionary object itself. Mutability refers to is hashed. Hence dictionaries are mutable but
the ability to change a value in place without keys are immutable and unique.
creating a new storage location for the changed
value. Question 6
Question 1 Output
Question 4 Question 5
What do you understand by mutability ? What Start with the list [8, 9, 10]. Do the following
does "in place" task mean ? using list functions:
58
6. Insert 25 at index 3 Question 7
Question 8 Example
statement is
Question 9
del list[<index>] # to remove element at index
60
What is the difference between a list and a 3. Now add 'Punjab' to the end of the list.
tuple ? 4. Define a variable states2 that is initialized
with 'Rajasthan', 'Gujarat', and 'Kerala'.
Answer
5. Add 'Odisha' to the beginning of the list
List states2.
6. Add 'Tripura' so that it is the third state in
Lists are mutable sequences of Python i.e., we the list states2.
can change elements of a list in place. 7. Add 'Haryana' to the list states2 so that it
appears before 'Gujarat'. Do this as if you
The syntax to create list is <list-name> = DO NOT KNOW where 'Gujarat' is in the list.
[value,.....] Hint. See what states2.index("Rajasthan")
Lists cannot be used as keys in dictionary. does. What can you conclude about what
listname.index(item) does ?
Lists cannot be used as elements of a set.
8. Remove the 5th state from the list states2
Lists are slower compared to tuples. and print that state's name.
Question 10
Answer
Question 11 Answer
Question 14 Question 16
63
What type of objects can be used as keys in sets, or other dictionaries, it cannot be used as a
dictionaries ? key in a dictionary.
Answer Question 18
Keys of a dictionary must be of immutable types Dictionary is a mutable type, which means you
such as can modify its contents ? What all is modifiable
in a dictionary ? Can you modify the keys of a
1. a Python string
dictionary ?
2. a number
3. a tuple (containing only immutable entries) Answer
for keys 'a', 'b' and 'c'. What happens if you try to
Output
index a nonexistent key (D['d']) ? What does
python do if you try to assign to a nonexistent D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}
key d.
Question 21
(e.g., D['d'] = 'spam') ?
What is sorting ? Name some popular sorting
Answer
techniques.
1. In this example, the dictionary D does not
Answer
contain the key 'd'. Therefore, attempting
to access this key by D['d'] results in a Sorting refers to arranging elements of a
KeyError because the key does not exist in sequence in a specific order — ascending or
the dictionary. descending.
2. If we try to assign a value to a nonexistent
key in a dictionary, python will create that Sorting Techniques are as follows :
key-value pair in the dictionary. In this
1. Bubble Sort
example, the key 'd' did not previously exist
2. Insertion Sort
in the dictionary D. When we attempted to
3. Selection Sort
assign the value 'spam' to the key 'd',
python created a new key-value pair 'd': 4. Heap Sort
'spam' in the dictionary D. 5. Quick Sort
What will be the output produced by following x[6] retrieves the character at index 6, which is
code fragments ? 'w'.
68
x[2:4] extracts the substring from index 2 up to Output
index 3, resulting in "ll". Enter a list of words: ["apple", "banana",
Hence, output of this line becomes w ll "orange", "kiwi"]
Average length of words: 5.25
print(x[2:-3], x[-4:-2]) —
x[2:-3] extracts the substring from index 2 up to
Explanation
the fourth last character, resulting in "llo wo".
x[-4:-2] extracts the substring from the fourth 1. The code prompts the user to enter a list of
last character to the third last character, words and assigns it to the variable word_list.
resulting in "or". 2. We iterate over word_list using for loop.
Hence, output of this line becomes llo wo or Inside the loop, length of each word gets
added to total_length variable.
Question 2
3. Average length is calculated by
Write a short Python code segment that adds up dividing total_length by the number of words
the lengths of all the words in a list and then in word_list.
prints the average (mean) length.
Question 3
Answer
Predict the output of the following code
word_list = eval(input("Enter a list of words: ")) snippet ?
total_length = 0
for word in word_list: a = [1, 2, 3, 4, 5]
total_length += len(word) print(a[3:0:-1])
average_length = total_length / len(word_list)
print("Average length of words:", average_length) Answer
69
Output Question 4(a)
70
list arr without newline characters because 1. is a list containing the numbers 9, 18,
Numbers
of end="" parameter. Then it prints the 27, and 36.
elements of the modified list arr, resulting 2. The outer for loop iterates over each
in 234566. element in the list Numbers.
3. The inner loop iterates over the range from
Question 4(b)
1 to the remainder of Num divided by 8.
Predict the output of the following code For example, if Num is 9, the range will be
snippet ? from 1 to 1 (9 % 8 = 1). If Num is 18, the
range will be from 1 to 2 (18 % 8 = 2), and
Numbers = [9, 18, 27, 36]
for Num in Numbers : so on. Then it prints the value of N,
for N in range(1, Num % 8) : followed by a "#", and ensures that the
print(N, "#", end=" ") output is printed on the same line by
print( )
setting end=" ".
Answer
4. After both loops, it prints an empty line,
effectively adding a newline character to
Output
the output.
1 # Question 5(a)
1 # 2 #
1 # 2 # 3 #
Find the errors. State reasons.
Explanation t = (1, "a", 9.2)
t[0] = 6
Answer
71
will raise a TypeError as tuples are
t[0] = 6 current range of the list t. As t has 3 elements so
immutable (i.e., their elements cannot be its indexes are 0, 1, 2 only.
changed after creation).
Question 5(d)
Question 5(b)
Find the errors. State reasons.
Find the errors. State reasons.
t = 'hello'
t = [1, "a", 9.2] t[0] = "H"
t[0] = 6
Answer
Answer
will raise an error because strings in
t[0] = "H"
There are no errors in this python code. Lists in python are immutable, meaning we cannot
python can contain elements of any type. As lists change individual characters in a string after it
are mutable so t[0] = 6 is also valid. has been created. Therefore, attempting to
assign a new value to t[0] will result in an error.
Question 5(c)
Question 5(e)
Find the errors. State reasons.
Find the errors. State reasons.
t = [1, "a", 9.2]
t[4] = 6 for Name in [Amar, Shveta, Parag]
IF Name[0] = 'S':
Answer print(Name)
74
rec = {"Name" : "Python", "Age" : "20", "Addr" : However, id1 == id2 will compare the contents of
"NJ", "Country" : "USA"}
id1 = id(rec) the two dictionaries pointed to by id1 and id2. As
del rec contents of both the dictionaries are same hence
rec = {"Name" : "Python", "Age" : "20", "Addr" :
"NJ", "Country" : "USA"}
it returns True. If in this code we add another
id2 = id(rec) line print(id1 is id2) then this line will
print(id1 == id2) print False as id1 and id2 point to two different
dictionary objects in memory.
1. True
2. False
Question 10
3. 1
4. Exception Write the output of the code given below :
my_dict = {"name" : "Aman", "age" : 26}
Answer my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
Output
Answer
True
Output
Explanation
dict_items([('name', 'Aman'), ('age', 27),
In the given python code snippet, id1 and id2 will ('address', 'Delhi')])
point to two different objects in memory as del
rec deleted the original dictionary whose id is Explanation
stored in id1 and created a new dictionary with
the same contents storing its id in id2.
75
A dictionary my_dict with two key-value pairs, 131313
'name': 'Aman' and 'age': 26 is initialized. Then ZAR#
updates the value associated with the key 'age'
Answer
to 27. Then adds a new key-value pair 'address':
'Delhi' to the dictionary my_dict. The items() method def display(my_list):
for item in my_list:
returns all of the items in the dictionary as a
if item.isdigit():
sequence of (key, value) tuples. In this case, it print(item * 3)
will print [('name', 'Aman'), ('age', 27), ('address', else:
print(item + '#')
'Delhi')]. display(my_list = eval(input("Enter the list :")))
Question 11 Output
Write a method in python to display the Enter the elements of the list separated by
elements of list thrice if it is a number and spaces:41 DROND GIRIRAJ 13 ZARA
414141
display the element terminated with '#' if it is not DROND#
number. GIRIRAJ#
131313
ZARA#
For example, if the content of list is as follows :
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA'] Explanation
The output should be
1. The code prompts the user to enter the
414141
elements of the list separated by spaces
DROND#
and stores the input as a single string in the
GIRIRAJ#
variable my_list.
76
2. Then splits the input string my_list into (i) isupper() method is used to check if a string
individual elements and stores them in a contains only uppercase letters.
new list called new_list.
(ii) len() gives the total length of the list.
3. Then for loop iterates over each element in
the new_list. Question 13
4. The isdigit() method is used to check if all
characters in the string are digits. If it's true What will be the output of the following code
(i.e., if the element consists only of digits), snippet ?
then it prints the element concatenated my_dict = {}
with itself three times. Otherwise, if the my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
element contains non-digit characters, it my_dict[(1,2)] = 12
prints the element concatenated with the sum = 0
character '#'. for k in my_dict:
sum += my_dict[k]
print(sum)
Question 12 print(my_dict)
Answer Explanation
77
1. An empty dictionary named my_dict is format or not and display if the phone number is
initialized. valid or not (i.e., contains just the digits and dash
2. my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, at specific places).
my_dict[(1,2)] = 12 these lines assign values to
the dictionary my_dict with keys as tuples. Solution
Since tuples are immutable, so they can be phNo = input("Enter the phone number: ")
used as keys in the dictionary. length = len(phNo)
if length == 12 \
3. The for loop iterates over the keys of the and phNo[3] == "-" \
dictionary my_dict. Inside the loop, the value and phNo[7] == "-" \
associated with each key k is added to the and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
variable sum. and phNo[8:].isdigit() :
4. sum and my_dict are printed. print("Valid Phone Number")
else :
print("Invalid Phone Number")
Type C: Programming
Practice/Knowledge based Questions Output
number of 10 digits and two dashes, with dashes Enter the phone number: 017-5A5-1212
after the area code and the next three numbers. Invalid Phone Number
For example, 017-555-1212 is a legal input.
Question 2
Display if the phone number entered is valid
78
Write a program that should prompt the user to elif ch.isalnum() :
alnumCount += 1
type some sentence(s) followed by "enter". It
should then print the original sentence(s) and alnumPercent = alnumCount / length * 100
the following statistics relating to the print("Original Sentences:")
sentence(s): print(str)
Solution Solution
Question 4
80
Write a short python code segment that prints Write a program that creates a list of all the
the longest word in a list of words. integers less than 100 that are multiples of 3 or
5.
Solution
Solution
my_list = eval(input("Enter the list : "))
longest_word = "" a = []
max_length = 0 for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
for word in my_list: a.append(i)
if len(word) > max_length: print(a)
max_length = len(word)
longest_word = word
Output
print("Longest word:", longest_word)
[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25,
27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51,
Output 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78,
80, 81, 84, 85, 87, 90, 93, 95, 96, 99]
Enter the list : ['red', 'yellow', 'green',
'blue']
Longest word: yellow Question 7
Enter the list : ['lion', 'elephant', 'tiger',
'monkey', 'hippopotamus'] Define two variables first and second so that first
Longest word: hippopotamus
= "Jimmy" and second = "Johny". Write a short
python code segment that swaps the values
Question 6
assigned to these two variables and prints the
results.
Solution
81
first = "Jimmy"
second = "Johny" tup = tuple(lst)
temp = first
first = second print("9 terms of Fibonacci series are:", tup)
second = temp
print("first =", first)
Output
print("second =", second)
9 terms of Fibonacci series are: (0, 1, 1, 2, 3,
Output 5, 8, 13, 21)
day_month_lst = []
83
Write a function called addDict(dict1, dict2) Write a program to sort a dictionary's keys using
which computes the union of two dictionaries. It Bubble sort and produce the sorted keys as a
should return a new dictionary, with all the items list.
in both its arguments (assumed to be
dictionaries). If the same key appears in both Solution
arguments, feel free to pick a value from either. my_dict = eval(input("Enter the dictionary: "))
keys = list(my_dict.keys())
Solution l = len(keys)
for i in range(l):
def addDict(dict1, dict2): for j in range(0, l - i - 1):
union_dict = {} if keys[j] > keys[j + 1]:
for key, value in dict1.items(): keys[j], keys[j + 1] = keys[j + 1],
union_dict[key] = value keys[j]
for key, value in dict2.items(): print("Sorted keys:",keys)
union_dict[key] = value
return union_dict Output
dict1 = {'a': 1, 'b': 2} Enter the dictionary: {'c':10, 'f':87, 'r':23,
dict2 = {'b': 3, 'c': 4} 'a':5}
result = addDict(dict1, dict2) Sorted keys: ['a', 'c', 'f', 'r']
print("Union of dict1 and dict2:", result)
Question 12
Output
Write a program to sort a dictionary's values
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}
using Bubble sort and produce the sorted values
Question 11 as a list.
84
Solution
Output
85