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

Python Revision Tour I and II Notes

Uploaded by

rizwana Umar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Revision Tour I and II Notes

Uploaded by

rizwana Umar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 85

GATEWAY INTERNATIONAL SCHOOL, NEELANKARAI 1.

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

3. Day_two Which of the following is not a keyword?


4. _2
1. eval
Answer 2. assert
3. nonlocal
2nd_day
4. pass
Reason — Variable names cannot begin with a
number, although they can contain numbers. Answer

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

Evaluate the expression given below if A = 16 What is the value of x?


and B = 15. x = int(13.25 + 4/2)
A % B // A
1. 17
1. 0.0 2. 14
2. 0 3. 15
3
4. 23 Reason — As both the operators are division
operators, the expression will be evaluated from
Answer left to right.
15 8/4/2 = 2/2 = 1.0
Reason — According to operator precedence, (8/4)/2
division will be done first followed by addition = 2/2
and then it will convert to integer. = 1.0

x = int(13.25 + 4/2) Question 11


x = int(13.25 + 2.0)
Which among the following list of operators has
x = int(15.45)
the highest precedence?
x = 15
+, -, **, %, /, <<, >>, |
Question 10
1. <<, >>
The expression 8/4/2 will evaluate equivalent to
2. **
which of the following expressions:
3. I
1. 8/(4/2) 4. %
2. (8/4)/2
Answer
Answer
**
(8/4)/2
4
Reason — ** has highest precedence. 2. print("hello\\example\\test.txt")
3. print("hello\"example\"test.txt")
Question 12
4. print("hello"\example"\test.txt")
Which of the following expressions results in an
error? Answer

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

Which of the following statement prints the Answer


shown output below? String
hello\example\test.txt

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

Reason — %, + are arithmetic operators. Reason —

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

Which of the following is valid arithmetic Answer


operator in Python :
ECM
1. //
2. ? Reason — The slicing will start from index 1 and
return at every alternative step.
3. <
4. and s[1] = E
s[3] = C
Answer s[5] = M
// output = ECM

Reason — // is valid arithmetic operator in Question 19


Python.
Which of the following is an incorrect Logical
Question 18
operator in Python?
7
1. not Fill in the Blanks
2. in
3. or Question 1
4. and
The smallest individual unit in a program is
Answer known as a token.

in Question 2

Reason — in is a membership operator. A token is also called a lexical unit.

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

("One") In a Python expression, when conversion of a


Reason — ("One") is a string data type. value's data type is done automatically by the

8
compiler without programmer's intervention, it Python's keywords cannot be used as variable
is called implicit type conversion. name.

Question 6 True/False Questions


The explicit conversion of an operand to a
Question 1
specific type is called type casting.
The expression int(x) implies that the variable x
Question 7
is converted to integer.
The pass statement is an empty statement in Answer
Python.
True
Question 8
Reason — int(x) explicitly converts variable x to
A break statement skips the rest of the loop and integer type.
jumps over to the statement following the loop.
Question 2
Question 9
The value of the expressions 4/(3*(2 - 1)) and
The continue statement skips the rest of the 4/3*(2 - 1) is the same.
loop statements and causes the next iteration of
the loop to take place. Answer

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

Reason — Parentheses has first precedence Question 5


then multiplication then division has
precedence.
10
A string can be surrounded by three sets of Answer
single quotation marks or by three sets of
False
double quotation marks.
Reason — Variables represent labelled storage
Answer
locations, whose values can be manipulated
True during program run.

Reason — A string literal is a sequence of Question 8


characters surrounded by single or double or
triple double quotes or triple single quotes. In Python, only if statement has else clause.

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)

Question 10 Both Assertion and Reason are true and Reason


is the correct explanation of Assertion.
In a nested loop, a break statement terminates
all the nested loops in one go. Explanation
In python, literal values have fixed memory
Answer locations and variable names reference them as
False values. This means that, although we can change
the value of an integer variable, the process
Reason — In nested loops, a break statement involves creating a new integer object with the
will terminate the very loop it appears in. updated value. Literal values, such as 10, have
fixed memory locations, and variables act as
Assertions and Reasons references to these values. When we assign a
new value to an integer variable, we are
Question 1 essentially creating a new object, and the
variable now points to this new object. Hence,
Assertion. Assigning a new value to an int
both Assertion and Reason are true and Reason
variable creates a new variable internally.
is the correct explanation of Assertion.
Reason. The int type is immutable data type of
Python. Question 2

Answer Assertion. """A Sample Python String""" is a valid


Python String.

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.

Assertion. The break statement can be used Answer


with all selection and iteration statements.
(e)
Reason. Using break with an if statement is of
Both Assertion and Reason are false.
no use unless the if statement is part of a
looping construct. Explanation
In python, the break statement can be used with
Answer
iteration statements only. Using break with
(e) conditional statements will result in syntax error
— SyntaxError: 'break' outside loop
Both Assertion and Reason are false.
Type A: Short Answer
Explanation Questions/Conceptual Questions
In python, the break statement can be used with
iteration statements only. Using break with Question 1
conditional statements will result in syntax error
— SyntaxError: 'break' outside loop What are tokens in Python? How many types of
tokens are allowed in Python? Exemplify your
Question 6 answer.
14
Answer reserved. They can have letters, digits and
underscore. They must begin with either a letter
The smallest individual unit in a program is
or underscore. For example, _chk, chess, trail,
known as a Token. Python has following tokens:
etc.
1. Keywords — Examples are import, for, in,
Question 3
while, etc.
2. Identifiers — Examples are MyFile, _DS, What are literals in Python? How many types of
DATE_9_7_77, etc. literals are allowed in Python?
3. Literals — Examples are "abc", 5, 28.5, etc.
Answer
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc. Literals are data items that have a fixed value.
The different types of literals allowed in Python
Question 2 are:

How are keywords different from identifiers? 1. String literals


2. Numeric literals
Answer
3. Boolean literals
Keywords are reserved words carrying special 4. Special literal None
meaning and purpose to the language
5. Literal collections
compiler/interpreter. For example, if, elif, etc.
are keywords. Identifiers are user defined names Question 4
for different parts of the program like variables,
objects, classes, functions, etc. Identifiers are not
15
State True or False : "Variable declaration is  For
implicit in Python."  do
Answer  4thCol
 totally
True.
 Row31
Reason — In Python, variable declaration is  _Amount
implicit. This means that we don't need to
explicitly declare the data type of a variable Answer
before using it. The type of a variable is  Price*Qty ⇒ Contains special character *
determined dynamically at runtime based on the  class ⇒ It is a keyword
assigned value. For example:
 4thCol ⇒ Begins with a digit
x = 5 # x is implicitly declared as an
integer Question 6
name = "Ravi" # name is implicitly declared as a
string
Find the invalid identifier from the following :
Question 5
1. MyName
Out of the following, find those identifiers, which 2. True
cannot be used for naming Variables or 3. 2ndName
Functions in a Python program: 4. My_Name

 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 ? **

Reason — Let's go through each option and see


1. Set
if its valid arithmetic operator or not:
2. None
3. Integer 1. ? — The question mark is not a valid
4. Real arithmetic operator in Python.
2. < — It is a relational operator.
Answer
3. ** — It is an arithmetic operator.
Real 4. and — It is a logical operator.

Reason — Real is not a standard built-in data Question 9


type in Python.
How are floating constants represented in
Question 8 Python? Give examples to support your answer.

Identify the valid arithmetic operator in Python Answer


from the following:
17
Floating constants are represented in Python in Answer
two forms — Fractional Form and Exponent
Operators are tokens that trigger some
form. Examples:
computation/action when applied to variables
1. Fractional Form — 2.0, 17.5, -13.0, - and other objects in an expression. Unary plus
0.00625 (+), Unary minus (-), Bitwise complement (~),
2. Exponent form — 152E05, 1.52E07, Logical negation (not) are a few examples of
0.152E08, -0.172E-3 unary operators. Examples of binary operators
are Addition (+), Subtraction (-), Multiplication (*),
Question 10 Division (/).
How are string-literals represented and Question 12
implemented in Python?
Which of the following are valid operators in
Answer Python:
A string-literal is represented as a sequence of
1. **
characters surrounded by quotes (single, double
2. */
or triple quotes). String-literals in Python are
3. like
implemented using Unicode.
4. ||
Question 11 5. is

What are operators ? What is their function? Give 6. ^


examples of some unary and binary operators. 7. between

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

1. True A block in Python, represents a group of


2. False statements executed as a single unit. Python
3. None uses indentation to create blocks of code.
Statements at same indentation level are part of
4. Null
same block/suite and constitute the body of the
Answer block.

True Question 18(a)

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

range(1,10) will generate a sequence like this [1,


Explanation
2, 3, 4, 4, 5, 6, 7, 8, 9]. p will be assigned each of
x will be assigned each of the values from the list the values from this sequence one by one and
one by one and that will get printed. that will get printed.

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:

Answer for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] :


print (Name)
if Name[0] == 'T' :
Loop executes for 5 times. break
else :
Output print ('Finished!')
print ('Got it!')
*
* Answer
*
*
Output
*
Jay
Explanation Finished!
Riya
range(1,3,1) returns [1, 2]. For first iteration of Finished!
Tanu
outer loop j is in range [0, 1] so inner loop Got it!
executes twice. For second iteration of outer
loop j is in range [0, 1, 2] so inner loop executes Explanation
3 times. This makes the total number of loop
The for loop iterates over each name in the list
executions as 2 + 3 = 5.
and prints it. If the name does not begin with the
Question 5 letter T, Finished! is printed after the name. If the
name begins with T, break statement is executed

35
that terminates the loop. Outside the loop, Got ⇒ n = 2n - n + 1
it! gets printed. ⇒n=n+1

Question 6 Therefore, inside the loop n is incremented by 1


in each iteration. Loop condition is n < 10 and
Is the loop in the code below infinite? How do initial value of n is 5. So after 5 iterations, n will
you know (for sure) before you run it? become 10 and the loop will terminate.
m = 3
n = 5 Type C: Programming
while n < 10:
m = n - 1 Practice/Knowledge based Questions
n = 2 * n - m
print(n, m)
Question 1
Answer
Write a program to print one of the words
The loop is not infinite. To know this without negative, zero, or positive, according to whether
running it we can analyze how n is changed variable x is less than zero, zero, or greater than
inside the loop in the following way: zero, respectively.

n=2*n-m Solution

Substituting value of m from m = n - 1, x = int(input("Enter x: "))

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

Enter x: 0 Write a Python program that calculates and


zero
prints the number of seconds in a year.
Enter x: 5
positive Solution

Question 2 days = 365


hours = 24
mins = 60
Write a program that returns True if the input secs = 60
number is an even number, False otherwise. secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)
Solution
Output
x = int(input("Enter a number: "))
Number of seconds in a year = 31536000
if x % 2 == 0:
print("True") Question 4
else:
print("False")
Write a Python program that accepts two
Output integers from the user and prints a message

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

a = int(input("Enter first number: ")) dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY",


b = int(input("Enter second number: ")) "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]

if a % b == 0: dayNum = int(input("Enter day number: "))


print(a, "is divisible by", b) firstDay = input("First day of year: ")
else:
print(a, "is not divisible by", b) if dayNum < 2 or dayNum > 365:
print("Invalid Input")
else:
Output
startDayIdx =
Enter first number: 15 dayNames.index(str.upper(firstDay))
Enter second number: 5 currDayIdx = dayNum % 7 + startDayIdx - 1
15 is divisible by 5
if currDayIdx >= 7:
Enter first number: 13 currDayIdx = currDayIdx - 7
Enter second number: 7
13 is not divisible by 7 print("Day on day number", dayNum, ":",
dayNames[currDayIdx])

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)

One foot equals 12 inches. Write a function that Output


accepts a length written in feet as an argument
Enter length in feet: 15
and returns this length written in inches. Write a Length in inches = 180
second function that asks the user for a number
of feet and returns this value. Write a third Question 7
function that accepts a number of inches and
Write a program that reads an integer N from
displays this to the screen. Use these three
the keyboard computes and displays the sum of
functions to write a program that asks the user
the numbers from N to (2 * N) if N is
for a number of feet and tells them the
nonnegative. If N is a negative number, then it's
corresponding number of inches.
the sum of the numbers from (2 * N) to N. The
starting and ending points are included in the
Solution
sum.
def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch
Solution

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

Question 8 Enter date in MMDDYYYY format: 12252019


December 25, 2019
Write a program that reads a date as an integer
Question 9
in the format MMDDYYYY. The program will call a
function that prints print out the date in the Write a program that prints a table on two
format <Month Name> <day>, <year>. columns — table that helps converting miles into
kilometers.
Sample run :
Enter date : 12252019 Solution
December 25, 2019
print('Miles | Kilometres')
print(1, "\t", 1.60934)
Solution for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)
months = ["January", "February", "March", "April",
"May", "June",
"July", "August", "September", "October", Output
"November", "December"]
Miles | Kilometres
dateStr = input("Enter date in MMDDYYYY format: ") 1 1.60934
40
10 16.0934 40 18.14
20 32.1868 50 22.675
30 48.2802 60 27.21
40 64.3736 70 31.745
50 80.467 80 36.28
60 96.5604 90 40.815
70 112.6538 100 45.35
80 128.7472
90 144.8406 Question 11
100 160.934
Write a program that reads two times in military
Question 10
format (0900, 1730) and prints the number of
Write another program printing a table with two hours and minutes between the two times.
columns that helps convert pounds in kilograms.
A sample run is being given below :
Solution Please enter the first time : 0900
Please enter the second time : 1730
print('Pounds | Kilograms') 8 hours 30 minutes
print(1, "\t", 0.4535)
for i in range(10, 101, 10):
print(i, "\t", i * 0.4535) Solution

ft = input("Please enter the first time : ")


Output st = input("Please enter the second time : ")

Pounds | Kilograms # Converts both times to minutes


1 0.4535 fMins = int(ft[:2]) * 60 + int(ft[2:])
10 4.535 sMins = int(st[:2]) * 60 + int(st[2:])
20 9.07
30 13.605 # Subtract the minutes, this will give

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

Please enter the first time : 0900 Answer


Please enter the second time : 1730
8 hours 30 minutes index
Please enter the first time : 0915 Reason — The index is the numbered position
Please enter the second time : 1005
0 hours 50 minutes of a letter in the string.

Question 2

The operator ............... tells if an element is


PYTHON-REVISION TOUR II LESSON NOTES present in a sequence or not.

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:

Reason — Index 5 is out of range because list <dictionary-name> = {<key>:<value>, <key>:<value>}

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

Question 18 Operator + when used with two strings, gives a


Suppose a tuple T is declared as T = (10, 12, 43, concatenated string.
39), which of the following is incorrect ?
Question 3

1. print(T[1]) Operator + when used with a string and an


2. T[2] = -29 integer gives an error.
3. print(max(T))
4. print(len(T)) Question 4

Answer Part of a string containing some contiguous


characters from the string is called string slice.
49
Question 5 The clear() function removes all the elements of
a list/dictionary.
The * operator when used with a list/string and
an integer, replicates the list/string. Question 11

Question 6 Creating a tuple from a set of values is


called packing.
Tuples or Strings are not mutable while lists are.
Question 12
Question 7
Creating individual values from a tuple's
Using list() function, you can make a true copy of
elements is called unpacking.
a list.
Question 13
Question 8
The keys() method returns all the keys in a
The pop() function is used to remove an item
dictionary.
from a list/dictionary.
Question 14
Question 9
The values() function returns all values from
The del statement can remove an individual item
Key : value pair of a dictionary.
or a slice from a list.
Question 15
Question 10

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

Assertion. Lists and Tuples are similar sequence Question 2

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

Both Assertion and Reason are true and Reason (b)


is the correct explanation of Assertion. Both Assertion and Reason are true but Reason
Explanation is not the correct explanation of Assertion.
Lists and tuples are similar sequence types in Explanation
python, but they are distinct data types. Both are In Python, strings are immutable, meaning once
54
they are created, their contents cannot be (a)
changed. Whenever we modify a string, python
Both Assertion and Reason are true and Reason
creates a new string object to hold the modified
is the correct explanation of Assertion.
contents, leaving the original string unchanged.
On the other hand, lists in python are mutable, Explanation
meaning we can modify their contents after they In Python, strings are immutable, meaning once
have been created. When we modify a list, they are created, their contents cannot be
python does not create a new list object. Instead, changed. Whenever we modify a string, python
it modifies the existing list object in place. Strings creates a new string object to hold the modified
are sequences of characters, and each character contents, leaving the original string unchanged.
in a string can be accessed by its index. Lists, on On the other hand, lists in python are mutable,
the other hand, can store any type of data, meaning we can modify their contents after they
including integers, floats, strings. have been created. When we modify a list,
python does not create a new list object. Instead,
Question 3
it modifies the existing list object in place.
Assertion. Modifying a string creates another
Question 4
string internally but modifying a list does not
create a new list. Assertion. Dictionaries are mutable, hence its
keys can be easily changed.
Reason. Strings are immutable types while lists
are mutable types of python. Reason. Mutability means a value can be
changed in place without having to create new
Answer
storage for the changed value.
55
Answer 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

Assertion. In Insertion Sort, a part of the array is


Question 5
always sorted.
Assertion. Dictionaries are mutable but their
Reason. In Insertion sort, each successive
keys are immutable.
element is picked and inserted at an appropriate
Reason. The values of a dictionary can change position in the sorted part of the array.
but keys of dictionary cannot be changed
Answer
because through them data is hashed.
56
(a) two-way index for each location. The index (also
called subscript) is the numbered position of a
Both Assertion and Reason are true and Reason
letter in the string. Indices begin 0 onwards in
is the correct explanation of Assertion.
the forward direction up to length-1 and -1,-2, ....
Explanation up to -length in the backward direction. This is
Insertion sort is a sorting algorithm that builds a called two-way indexing.
sorted list, one element at a time from the
Question 2
unsorted list by inserting the element at its
correct position in sorted list. In Insertion sort, Write a python script that traverses through an
each successive element is picked and inserted input string and prints its characters in different
at an appropriate position in the previously lines - two characters per line.
sorted array.
Answer
Type A: Short Answer name = input("Enter name:")
Questions/Conceptual Questions for i in range(0, len(name), 2):
print(name[i:i+2])

Question 1 Output

What is the internal structure of python strings ? Enter name:python


py
Answer th
on
Strings in python are stored as individual
Question 3
characters in contiguous memory locations, with
57
Discuss the utility and significance of Lists, object in a new memory location with the
briefly. updated values. Examples of mutable objects in
python include lists, dictionaries.
Answer
In python, "in place" tasks refer to operations
A list is a standard data type of python that can that modify an object directly without creating a
store a sequence of values belonging to any new object or allocating additional memory. For
type. Lists are mutable i.e., we can change example, list methods like append(), extend(),
elements of a list in place. Their dynamic nature and pop() perform operations in place,
allows for flexible manipulation, including modifying the original list, while string methods
appending, inserting, removing, and slicing like replace() do not modify the original string in
elements. Lists offer significant utility in data place but instead create a new string with the
storage, iteration, and manipulation tasks. desired changes.

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:

Answer 1. Set the second entry (index 1) to 17


2. Add 4, 5 and 6 to the end of the list
Mutability means that the value of an object can
3. Remove the first entry from the list
be updated by directly changing the contents of
4. Sort the list
the memory location where the object is stored.
There is no need to create another copy of the 5. Double the list

58
6. Insert 25 at index 3 Question 7

Answer What are the two ways to add something to a list


? How are they different ?
listA = [8, 9, 10]
Answer
1. listA[1] = 17
The two methods to add something to a list are:
2. listA.extend([4, 5, 6])
3. listA.pop(0) 1. append method — The syntax of append
4. listA.sort() method is list.append(item).
5. listA = listA * 2 2. extend method — The syntax of extend
method is list.extend(<list>).
6. listA.insert(3, 25)
Difference
Question 6
The difference between the append() and
What's a[1 : 1] if a is a string of at least two extend() methods in python is that append()
characters ? And what if string is shorter ? adds one element at the end of a list, while
extend() can add multiple elements, given in the
Answer form of a list, to a list.
a[x:y] returns a slice of the sequence from index Example
x to y - 1. So, a[1 : 1] will return an empty list
irrespective of whether the list has two elements append method:
or less as a slice from index 1 to index 0 is an lst1 = [10, 12, 14]
invalid range. lst1.append(16)
59
print(lst1) del list[<start>:<stop>] # to remove elements in
list slice
Output — [10, 12, 14, 16]
Difference
extend method:
The difference between the pop() and del is that
t1 = ['a', 'b', 'c']
t2 = ['d', 'e'] pop() method is used to remove single item from
t1.extend(t2) the list, not list slices whereas del statement is
print(t1)
used to remove an individual item, or to remove
Output — ['a', 'b', 'c', 'd', 'e'] all items identified by a slice.

Question 8 Example

What are the two ways to remove something pop() method:


from a list? How are they different ? t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']
ele1 = t1.pop(0)
Answer print(ele1)

The two ways to remove something from a list Output — 'k'


are: del statement:
lst = [1, 2, 3, 4, 5]
1. pop method — The syntax of pop method del lst[2:4]
is List.pop(<index>). print(lst)

2. del statement — The syntax of del Output — [1, 2, 5]

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

In the Python shell, do the following : 1. states = []


2. states.append('Delhi')
1. Define a variable named states that is an 3. states.append('Punjab')
empty list.
4. states2 = ['Rajasthan', 'Gujarat', 'Kerala']
2. Add 'Delhi' to the list.
61
5. states2.insert(0,'Odisha') 1. what is the difference (if any) between a * 3
6. states2.insert(2,'Tripura') and (a, a, a) ?
7. a = states2.index('Gujarat') 2. Is a * 3 equivalent to a + a + a ?
states2.insert(a - 1,'Haryana') 3. what is the meaning of a[1:1] ?
8. b = states2.pop(4) 4. what is the difference between a[1:2] and
print(b) a[1:1] ?

Question 11 Answer

Discuss the utility and significance of Tuples, 1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)


briefly. (a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple
Answer whereas (a, a, a) creates nested tuple.
Tuples are used to store multiple items in a 2. Yes, both a * 3 and a + a + a will result in (1,
single variable. It is a collection which is ordered 2, 3, 1, 2, 3, 1, 2, 3).
and immutable i.e., the elements of the tuple 3. This colon indicates (:) simple slicing
can't be changed in place. Tuples are useful operator. Tuple slicing is basically used to
when values to be stored are constant and need obtain a range of items.
to be accessed quickly. tuple[Start : Stop] ⇒ returns the portion of
the tuple from index Start to index Stop
Question 12 (excluding element at stop).
a[1:1] ⇒ This will return empty list as a slice
If a is (1, 2, 3)
from index 1 to index 0 is an invalid range.
62
4. Both are creating tuple slice with elements Write a Python statement to declare a Dictionary
falling between indexes start and stop. named ClassRoll with Keys as 1, 2, 3 and
a[1:2] ⇒ (2,) corresponding values as 'Reena', 'Rakesh',
It will return elements from index 1 to 'Zareen' respectively.
index 2 (excluding element at 2).
Answer
a[1:1] ⇒ ()
a[1:1] specifies an invalid range as start and ClassRoll = {1:'Reena', 2:'Rakesh', 3:'Zareen'}
stop indexes are the same. Hence, it will
return an empty list. Question 15

Why is a dictionary termed as an unordered


Question 13
collection of objects ?
What is the difference between (30) and (30,) ?
Answer
Answer
A dictionary is termed as an unordered
a = (30) ⇒ It will be treated as an integer collection of objects because the elements in a
expression, hence a stores an integer 30, not a dictionary are not stored in any particular order.
tuple. Unlike string, list and tuple, a dictionary is not a
a = (30,) ⇒ It is considered as single element sequence. For a dictionary, the printed order of
tuple since a comma is added after the element elements is not the same as the order in which
to convert it into a tuple. the elements are stored.

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

Question 17 Yes, we can modify the contents of a dictionary.


Values of key-value pairs are modifiable in
Though tuples are immutable type, yet they dictionary. New key-value pairs can also be
cannot always be used as keys in a dictionary. added to an existing dictionary and existing key-
What is the condition to use tuples as a key in a value pairs can be removed.
dictionary ? However, the keys of the dictionary cannot be
changed. Instead we can add a new key : value
Answer
pair with the desired key and delete the previous
For a tuple to be used as a key in a dictionary, all one.
its elements must be immutable as well. If a For example:
tuple contains mutable elements, such as lists, d = { 1 : 1 }
d[2] = 2
print(d)
64
d[1] = 3 Answer
print(d)
d[3] = 2
print(d) del D deletes the entire dictionary D. After
del d[2] executing del D, the variable D is no longer
print(d) defined, and any attempt to access D will result in
a NameError.
Output
del D[<key>] deletes the key-value pair associated
{1: 1, 2: 2} with the specified key from the dictionary D. After
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2} executing del D[<key>], the dictionary D still exists,
{1: 3, 3: 2} but the specified key and its corresponding value
are removed from the dictionary.
Explanation For example:
d is a dictionary which contains one key-value d = {1: 'a' , 2 : 'b'}
pair. del d[2]
print(d)
d[2] = 2 adds new key-value pair to d. del d
d[1] = 3 modifies value of key 1 from 1 to 3. print(d)
d[3] = 2 adds new key-value pair to d.
Output
del d[2] deletes the key 2 and its corresponding
value. {1:'a'}
NameError: name 'd' is not defined.
Question 19
Question 20
How is del D and del D[<key>] different from one
another if D is a dictionary ?
65
Create a dictionary named D with three entries, D['d'] = 'spam'

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

D = {'a' : 1, 'b' : 2, 'c' : 3} Question 22


66
Discuss Bubble sort and Insertion sort print(x, y)
x = "hello" + "world"
techniques. y = len(x)
print(y, x)
Answer
Answer
Bubble Sort :
In Bubble sort, the adjoining values are Output
compared and exchanged if they are not in hellohellohello 123
proper order. This process is repeated until the 10 helloworld
entire array is sorted.
Explanation
Insertion Sort :
Insertion sort is a sorting algorithm that builds a str(123) converts the number 123 to string and
sorted list one element at a time from the stores in y so y becomes "123". "hello" * 3
unsorted list by inserting the element at its repeats "hello" 3 times and stores it in x so x
correct position in sorted list. becomes "hellohellohello".

"hello" + "world" concatenates both the strings


Type B: Application Based Questions
so x becomes "helloworld". As "helloworld"
contains 10 characters so len(x) returns 10.
Question 1(a)
Question 1(b)
What will be the output produced by following
code fragments ? What will be the output produced by following
y = str(123) code fragments ?
x = "hello" \* 3
67
x = "hello" + \ x = "hello world"
"to Python" + \ print(x[:2], x[:-2], x[-2:])
"world" print(x[6], x[2:4])
for char in x : print(x[2:-3], x[-4:-2])
y = char
print(y, ':', end=" ") Answer
Answer
Output

Output he hello wor ld


w ll
h : e : l : l : o : t : o : : P : y : t : h : llo wo or
o : n : w : o : r : l : d :
Explanation
Explanation

print(x[:2], x[:-2], x[-2:])
The code concatenates three strings "hello", "to x[:2] extracts the substring from the beginning of
Python", and "world" into the variable x. Then, it x up to index 1, resulting in "he".
iterates over each character in x using a for loop. x[:-2] extracts the substring from the beginning
For each character, it assigns it to the of x up to the third last character, resulting in
variable y and prints y followed by a colon and "hello wor".
space, all on the same line due to the end=" x[-2:] extracts the substring from the last two
" parameter.
characters of x until the end, resulting in "ld".
Hence, output of this line becomes he hello wor ld
Question 1(c)
print(x[6], x[2:4]) —

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)

[4, 3, 2] Predict the output of the following code snippet?

Explanation arr = [1, 2, 3, 4, 5, 6]


for i in range(1, 6):
arr[i - 1] = arr[i]
The slicing notation a[start:stop:step] extracts a for i in range(0, 6):
portion of the list from index start to stop-1 with a print(arr[i], end = "")
specified step. In the slicing part a[3:0:-1]:
Answer
 start is 3, which corresponds to the element
Output
with value 4.
 stop is 0, but as element at stop index is 234566
excluded so slicing goes up to index 1.
Explanation
 step is -1, indicating that we want to step
backward through the list. 1. is initialised as a list with elements [1, 2,
arr
3, 4, 5, 6].
Putting it together:
2. for loop iterates over the indices from 1 to
a[3:0:-1] 5. For each index i, it assigns the value
This extracts elements from index 3 to (0+1) in of arr[i] to arr[i - 1], effectively shifting each
reverse order with a step of -1. element one position to the left. After this
loop, the list arr becomes [2, 3, 4, 5, 6, 6].
The output of the code will be: 3. Second for loop iterates over the indices
[4, 3, 2] from 0 to 5 and prints each element of the

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)

will raise an error as we are trying to


t[4] = 6 Answer
change the value at index 4 but it is outside the
72
The errors in this code are: 2. The end index being 0 means that the last
element of the list is missed as the list will
1. In the list [Amar, Shveta, Parag], each element be iterated till index 1 only.
should be enclosed in quotes because they
are strings. The corrected python code is :
2. The equality comparison operator is '=='
for i in range(len(words)-1, -1, -1):
instead of = for checking equality. print(words[i], end=' ')
3. if statement should be lowercase.
Question 7
Question 6
What would be the output of following code if
Assuming words is a valid list of words, the ntpl = ("Hello", "Nita", "How's", "life ?") ?
program below tries to print the list in reverse. (a, b, c, d) = ntpl
Does it have an error ? If so, why ? (Hint. There print("a is:", a)
print("b is:", b)
are two problems with the code.)
print("c is:", c)
for i in range(len(words), 0, -1): print("d is:", d)
print(words[i], end=' ') ntpl = (a, b, c, d)
print(ntpl[0][0] + ntpl[1][1], ntpl[1])
Answer
Answer
There are two issue in range(len(words), 0, -1) :
Output
1. The start index len(words) is invalid for the a is: Hello
list words as it will have indexes from 0 b is: Nita
to len(words) - 1. c is: How's
d is: life ?
73
Hi Nita What will be the output of the following code ?

Explanation tuple_a = 'a', 'b'


tuple_b = ('a', 'b')
print (tuple_a == tuple_b)
ntpl is a tuple containing 4 elements. The
statement (a, b, c, d) = ntpl unpacks the tuple Answer
ntpl into the variables a, b, c, d. After that, the
values of the variables are printed. Output
The statement ntpl = (a, b, c, d) forms a tuple True
with values of variables a, b, c, d and assigns it to
ntpl. As these variables were not modified, so Explanation
effectively ntpl still contains the same values as
Tuples can be declared with or without
in the first statement.
parentheses (parentheses are optional). Here,
ntpl[0] ⇒ "Hello"
tuple_a is declared without parentheses where
∴ ntpl[0][0] ⇒ "H"
as tuple_b is declared with parentheses but both
ntpl[1] ⇒ "Nita" are identical. As both the tuples contain same
∴ ntpl[1][1] ⇒"i" values so the equality operator ( == ) returns
true.
and ntpl[1][1] concatenates to form "Hi".
ntpl[0][0]
Thus ntpl[0][0]+ntpl[1][1], ntpl[1] will return "Hi Nita Question 9
".
What will be the output of the following code
Question 8 snippet ?

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)

Name the function/method required to Answer

(i) check if a string contains only uppercase Output


letters.
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
(ii) gives the total length of the list.

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

Enter the phone number: 017-555-1212


Question 1 Valid Phone Number

Write a program that prompts for a phone =====================================

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)

 Number of words print("Number of words =", (spaceCount + 1))


print("Number of characters =", (length))
 Number of characters (including white- print("Alphanumeric Percentage =", alnumPercent)
space and punctuation)
 Percentage of characters that are alpha Output
numeric Enter a few sentences: Python was conceived in the
late 1980s by Guido van Rossum at Centrum Wiskunde
Hints & Informatica (CWI) in the Netherlands. Its
implementation began in December 1989. Python 3.0
was released on 3 December 2008.
 Assume any consecutive sequence of non- Original Sentences:
blank characters in a word. Python was conceived in the late 1980s by Guido
van Rossum at Centrum Wiskunde & Informatica (CWI)
in the Netherlands. Its implementation began in
Solution December 1989. Python 3.0 was released on 3
December 2008.
str = input("Enter a few sentences: ")
Number of words = 34
length = len(str)
Number of characters = 205
spaceCount = 0
Alphanumeric Percentage = 80.48780487804879
alnumCount = 0

for ch in str : Question 3


if ch.isspace() :
spaceCount += 1
79
Write a program that takes any two lists L and M Write a program that rotates the elements of a
of the same size and adds their elements list so that the element at the first index moves
together to form a new list N whose elements to the second index, the element in the second
are sums of the corresponding elements in L and index moves to the third index, etc., and the
M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], element in the last index moves to the first
then N should equal [4, 6, 13]. index.

Solution Solution

print("Enter two lists of same size") l = eval(input("Enter the list: "))


L = eval(input("Enter first list(L): ")) print("Original List")
M = eval(input("Enter second list(M): ")) print(l)
N = []
l = l[-1:] + l[:-1]
for i in range(len(L)):
N.append(L[i] + M[i]) print("Rotated List")
print(l)
print("List N:")
print(N)
Output

Output Enter the list: [8, 10, 13, 25, 7, 11]


Original List
Enter two lists of same size [8, 10, 13, 25, 7, 11]
Enter first list(L): [3, 1, 4] Rotated List
Enter second list(M): [1, 5, 9] [11, 8, 10, 13, 25, 7]
List N:
[4, 6, 13] Question 5

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)

first = Johny Question 9


second = Jimmy
Create a dictionary whose keys are month
Question 8
names and whose values are the number of
Write a python program that creates a tuple days in the corresponding months.
storing first 9 terms of Fibonacci series.
(a) Ask the user to enter a month name and use
Solution
the dictionary to tell them how many days are in
the month.
lst = [0,1]
a = 0 (b) Print out all of the keys in alphabetical order.
b = 1
c = 0
(c) Print out all of the months with 31 days.
for i in range(7):
c = a + b (d) Print out the (key-value) pairs sorted by the
a = b number of days in each month.
b = c
lst.append(c)
Solution
82
days_in_months = { for i in days_in_months:
"january":31, day_month_lst.append([days_in_months[i], i])
"february":28, day_month_lst.sort()
"march":31,
"april":30, month_day_lst =[]
"may":31, for i in day_month_lst:
"june":30, month_day_lst.append([i[1], i[0]])
"july":31,
"august":31, sorted_days_in_months = dict(month_day_lst)
"september":30, print()
"october":31, print("Months sorted by days:",
"november":30, sorted_days_in_months)
"december":31
}
Output
m = input("Enter name of month: ") Enter name of month: may
There are 31 days in may
if m not in days_in_months: Months in alphabetical order are: ['april',
print("Please enter the correct month") 'august', 'december', 'february', 'january',
else: 'july', 'june', 'march', 'may', 'november',
print("There are", days_in_months[m], "days 'october', 'september']
in", m) Months with 31 days: january march may july august
october december
print("Months in alphabetical order are:", Months sorted by days: {'february': 28, 'april':
sorted(days_in_months)) 30, 'june': 30, 'november': 30, 'september': 30,
'august': 31, 'december': 31, 'january': 31,
print("Months with 31 days:", end=" ") 'july': 31, 'march': 31, 'may': 31, 'october': 31}
for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ") Question 10

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

my_dict = eval(input("Enter the dictionary: "))


values = list(my_dict.values())
l = len(values)
for i in range(l):
for j in range(0, l - i - 1):
if values[j] > values[j + 1]:
# Swap values
values[j], values[j + 1] = values[j +
1], values[j]
print("Sorted values:", values)

Output

Enter the dictionary: {'w':34, 'a':5, 'g':45,


't':21}
Sorted values: [5, 21, 34, 45]

85

You might also like