0% found this document useful (0 votes)
49 views52 pages

Sumitha Arora 2 & 3

Uploaded by

gangsanjay45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views52 pages

Sumitha Arora 2 & 3

Uploaded by

gangsanjay45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

LESSON.

2 PYTHON REVISION TOUR:2


Type A: Short Answer Questions/Conceptual
Questions

Question 1

What is the internal structure of python strings ?

Answer

Strings in python are stored as individual characters in contiguous memory locations, with two-way
index for each location. The index (also called subscript) is the numbered position of a letter in the
string. Indices begin 0 onwards in the forward direction up to length-1 and -1,-2, .... up to -length in
the backward direction. This is called two-way indexing.

Question 2

Write a python script that traverses through an input string and prints its characters in different
lines - two characters per line.

Answer

name = input("Enter name:")


for i in range(0, len(name), 2):
print(name[i:i+2])

Output

Enter name:python
py
th
on

Question 3

Discuss the utility and significance of Lists, briefly.

Answer

A list is a standard data type of python that can store a sequence of values belonging to any type.
Lists are mutable i.e., we can change elements of a list in place. Their dynamic nature allows for
flexible manipulation, including appending, inserting, removing, and slicing elements. Lists offer
significant utility in data storage, iteration, and manipulation tasks.

Question 4

What do you understand by mutability ? What does "in place" task mean ?

Answer

Mutability means that the value of an object can be updated by directly changing the contents of
the memory location where the object is stored. There is no need to create another copy of the
object in a new memory location with the updated values. Examples of mutable objects in python
include lists, dictionaries.
In python, "in place" tasks refer to operations that modify an object directly without creating a new
object or allocating additional memory. For example, list methods like append(), extend(), and
pop() perform operations in place, modifying the original list, while string methods like replace() do
not modify the original string in place but instead create a new string with the desired changes.

Question 5

Start with the list [8, 9, 10]. Do the following using list functions:

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


2. Add 4, 5 and 6 to the end of the list
3. Remove the first entry from the list
4. Sort the list
5. Double the list
6. Insert 25 at index 3

Answer

listA = [8, 9, 10]

1. listA[1] = 17
2. listA.extend([4, 5, 6])
3. listA.pop(0)
4. listA.sort()
5. listA = listA * 2
6. listA.insert(3, 25)

Question 6

What's a[1 : 1] if a is a string of at least two characters ? And what if string is shorter ?

Answer

a[x:y] returns a slice of the sequence from index x to y - 1. So, a[1 : 1] will return an empty list
irrespective of whether the list has two elements or less as a slice from index 1 to index 0 is an
invalid range.

Question 7

What are the two ways to add something to a list ? How are they different ?

Answer

The two methods to add something to a list are:

1. append method — The syntax of append method is list.append(item) .


2. extend method — The syntax of extend method is list.extend(<list>) .
Difference

The difference between the append() and extend() methods in python is that append() adds one
element at the end of a list, while extend() can add multiple elements, given in the form of a list, to
a list.

Example
append method:

lst1 = [10, 12, 14]


lst1.append(16)
print(lst1)

Output — [10, 12, 14, 16]


extend method:

t1 = ['a', 'b', 'c']


t2 = ['d', 'e']
t1.extend(t2)
print(t1)

Output — ['a', 'b', 'c', 'd', 'e']

Question 8

What are the two ways to remove something from a list? How are they different ?

Answer

The two ways to remove something from a list are:

1. pop method — The syntax of pop method is List.pop(<index>) .

2. del statement — The syntax of del statement is

del list[<index>] # to remove element at index


del list[<start>:<stop>] # to remove elements in list slice
Difference

The difference between the pop() and del is that pop() method is used to remove single item from
the list, not list slices whereas del statement is used to remove an individual item, or to remove all
items identified by a slice.

Example

pop() method:

t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']


ele1 = t1.pop(0)
print(ele1)

Output — 'k'
del statement:

lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)

Output — [1, 2, 5]

Question 9

What is the difference between a list and a tuple ?


Answer

List Tuple

Lists are mutable sequences of Python i.e., we can Tuples are immutable sequences of Python i.e., we
change elements of a list in place. cannot change elements of a tuple in place.

The syntax to create list is <list-name> = The syntax to create tuple is <tuple-name> =
[value,.....] (value, ....)
Lists cannot be used as keys in dictionary. Tuples can be used as keys in dictionary.
Lists cannot be used as elements of a set. Tuples can be used as elements of a set.
Lists are slower compared to tuples. Tuples are faster compared to lists.

Question 10

In the Python shell, do the following :

1. Define a variable named states that is an empty list.


2. Add 'Delhi' to the list.
3. Now add 'Punjab' to the end of the list.
4. Define a variable states2 that is initialized with 'Rajasthan', 'Gujarat', and 'Kerala'.
5. Add 'Odisha' to the beginning of the list states2.
6. Add 'Tripura' so that it is the third state in the list states2.
7. Add 'Haryana' to the list states2 so that it appears before 'Gujarat'. Do this as if you DO
NOT KNOW where 'Gujarat' is in the list. Hint. See what states2.index("Rajasthan") does.
What can you conclude about what listname.index(item) does ?
8. Remove the 5th state from the list states2 and print that state's name.

Answer

1. states = []
2. states.append('Delhi')
3. states.append('Punjab')
4. states2 = ['Rajasthan', 'Gujarat', 'Kerala']
5. states2.insert(0,'Odisha')
6. states2.insert(2,'Tripura')
7. a = states2.index('Gujarat')
states2.insert(a - 1,'Haryana')
8. b = states2.pop(4)
print(b)

Question 11

Discuss the utility and significance of Tuples, briefly.

Answer

Tuples are used to store multiple items in a single variable. It is a collection which is ordered and
immutable i.e., the elements of the tuple can't be changed in place. Tuples are useful when values
to be stored are constant and need to be accessed quickly.
Question 12

If a is (1, 2, 3)

1. what is the difference (if any) between a * 3 and (a, a, a) ?


2. Is a * 3 equivalent to a + a + a ?
3. what is the meaning of a[1:1] ?
4. what is the difference between a[1:2] and a[1:1] ?

Answer

1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple.
2. Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
3. This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a

tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop
range of items.

a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range.
(excluding element at stop).

a[1:2] ⇒ (2,)
4. Both are creating tuple slice with elements falling between indexes start and stop.

a[1:1] ⇒ ()
It will return elements from index 1 to index 2 (excluding element at 2).

a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will
return an empty list.

Question 13

What is the difference between (30) and (30,) ?

Answer

a = (30) ⇒ It will be treated as an integer expression, hence a stores an integer 30, not a tuple.
a = (30,) ⇒ It is considered as single element tuple since a comma is added after the element to
convert it into a tuple.

Question 14

Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1, 2, 3 and
corresponding values as 'Reena', 'Rakesh', 'Zareen' respectively.

Answer

ClassRoll = {1:'Reena', 2:'Rakesh', 3:'Zareen'}

Question 15

Why is a dictionary termed as an unordered collection of objects ?

Answer

A dictionary is termed as an unordered collection of objects because the elements in a dictionary


are not stored in any particular order. Unlike string, list and tuple, a dictionary is not a sequence.
For a dictionary, the printed order of elements is not the same as the order in which the elements
are stored.
Question 16

What type of objects can be used as keys in dictionaries ?

Answer

Keys of a dictionary must be of immutable types such as

1. a Python string
2. a number
3. a tuple (containing only immutable entries)

Question 17

Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is
the condition to use tuples as a key in a dictionary ?

Answer

For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a
tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a
key in a dictionary.

Question 18

Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable in a
dictionary ? Can you modify the keys of a dictionary ?

Answer

Yes, we can modify the contents of a dictionary.


Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to
an existing dictionary and existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value pair
with the desired key and delete the previous one.
For example:

d = { 1 : 1 }
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)

Output

{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}

Explanation
d is a dictionary which contains one key-value pair.
d[2] = 2 adds new key-value pair to d.
d[1] = 3 modifies value of key 1 from 1 to 3.
d[3] = 2 adds new key-value pair to d.
del d[2] deletes the key 2 and its corresponding value.

Question 19

How is del D and del D[<key>] different from one another if D is a dictionary ?

Answer

del D deletes the entire dictionary D. After executing del D, the variable D is no longer
defined, and any attempt to access D will result in a NameError.
del D[<key>] deletes the key-value pair associated with the specified key from the
dictionary D. After executing del D[<key>], the dictionary D still exists, but the specified key
and its corresponding value are removed from the dictionary.
For example:

d = {1: 'a' , 2 : 'b'}


del d[2]
print(d)
del d
print(d)

Output

{1:'a'}
NameError: name 'd' is not defined.

Question 20

Create a dictionary named D with three entries, for keys 'a', 'b' and 'c'. What happens if you try to
index a nonexistent key (D['d']) ? What does python do if you try to assign to a nonexistent key d.
(e.g., D['d'] = 'spam') ?

Answer

1. In this example, the dictionary D does not contain the key 'd'. Therefore, attempting to
access this key by D['d'] results in a KeyError because the key does not exist in the
dictionary.
2. If we try to assign a value to a nonexistent key in a dictionary, python will create that key-
value pair in the dictionary. In this example, the key 'd' did not previously exist in the
dictionary D. When we attempted to assign the value 'spam' to the key 'd', python created
a new key-value pair 'd': 'spam' in the dictionary D.

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


D['d'] = 'spam'

Output

D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}

Question 21
What is sorting ? Name some popular sorting techniques.

Answer

Sorting refers to arranging elements of a sequence in a specific order — ascending or descending.

Sorting Techniques are as follows :

1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Heap Sort
5. Quick Sort

Question 22

Discuss Bubble sort and Insertion sort techniques.

Answer

Bubble Sort :
In Bubble sort, the adjoining values are compared and exchanged if they are not in proper order.
This process is repeated until the entire array is sorted.

Insertion Sort :
Insertion sort is a sorting algorithm that builds a sorted list one element at a time from the unsorted
list by inserting the element at its correct position in sorted list.

Type B: Application Based Questions

Question 1(a)

What will be the output produced by following code fragments ?

y = str(123)
x = "hello" \* 3
print(x, y)
x = "hello" + "world"
y = len(x)
print(y, x)
Answer

Output

hellohellohello 123
10 helloworld

Explanation

str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3 repeats
"hello" 3 times and stores it in x so x becomes "hellohellohello".

"hello" + "world" concatenates both the strings so x becomes "helloworld". As "helloworld" contains
10 characters so len(x) returns 10.
Question 1(b)

What will be the output produced by following code fragments ?

x = "hello" + \
"to Python" + \
"world"
for char in x :
y = char
print(y, ':', end=" ")
Answer

Output

h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o :
r : l : d :

Explanation

The code concatenates three strings "hello", "to Python", and "world" into the variable x. Then, it
iterates over each character in x using a for loop. For each character, it assigns it to the
variable y and prints y followed by a colon and space, all on the same line due to the end="
" parameter.

Question 1(c)

What will be the output produced by following code fragments ?

x = "hello world"
print(x[:2], x[:-2], x[-2:])
print(x[6], x[2:4])
print(x[2:-3], x[-4:-2])
Answer

Output

he hello wor ld
w ll
llo wo or

Explanation

print(x[:2], x[:-2], x[-2:]) —


x[:2] extracts the substring from the beginning of x up to index 1, resulting in "he".
x[:-2] extracts the substring from the beginning of x up to the third last character, resulting in "hello
wor".
x[-2:] extracts the substring from the last two characters of x until the end, resulting in "ld".
Hence, output of this line becomes he hello wor ld
print(x[6], x[2:4]) —
x[6] retrieves the character at index 6, which is 'w'.
x[2:4] extracts the substring from index 2 up to index 3, resulting in "ll".
Hence, output of this line becomes w ll
print(x[2:-3], x[-4:-2]) —
x[2:-3] extracts the substring from index 2 up to the fourth last character, resulting in "llo wo".
x[-4:-2] extracts the substring from the fourth last character to the third last character, resulting in
"or".
Hence, output of this line becomes llo wo or

Question 2

Write a short Python code segment that adds up the lengths of all the words in a list and then
prints the average (mean) length.

Answer

word_list = eval(input("Enter a list of words: "))


total_length = 0
for word in word_list:
total_length += len(word)
average_length = total_length / len(word_list)
print("Average length of words:", average_length)

Output

Enter a list of words: ["apple", "banana", "orange", "kiwi"]


Average length of words: 5.25

Explanation

1. The code prompts the user to enter a list of words and assigns it to the
variable word_list.
2. We iterate over word_list using for loop. Inside the loop, length of each word gets
added to total_length variable.
3. Average length is calculated by dividing total_length by the number of words
in word_list.

Question 3

Predict the output of the following code snippet ?

a = [1, 2, 3, 4, 5]
print(a[3:0:-1])
Answer

Output

[4, 3, 2]

Explanation

The slicing notation a[start:stop:step] extracts a portion of the list from


index start to stop-1 with a specified step. In the slicing part a[3:0:-1]:

 start is 3, which corresponds to the element with value 4.


 stop is 0, but as element at stop index is excluded so slicing goes up to index 1.
 step is -1, indicating that we want to step backward through the list.

Putting it together:

a[3:0:-1]
This extracts elements from index 3 to (0+1) in reverse order with a step of -1.

The output of the code will be:

[4, 3, 2]

Question 4(a)

Predict the output of the following code snippet?

arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = "")
Answer

Output

234566

Explanation

1. arr is initialised as a list with elements [1, 2, 3, 4, 5, 6].


2. for loop iterates over the indices from 1 to 5. For each index i, it assigns the value
of arr[i] to arr[i - 1], effectively shifting each element one position to the left.
After this loop, the list arr becomes [2, 3, 4, 5, 6, 6] .
3. Second for loop iterates over the indices from 0 to 5 and prints each element of the
list arr without newline characters because of end="" parameter. Then it prints the
elements of the modified list arr, resulting in 234566.

Question 4(b)

Predict the output of the following code snippet ?

Numbers = [9, 18, 27, 36]


for Num in Numbers :
for N in range(1, Num % 8) :
print(N, "#", end=" ")
print( )
Answer

Output

1 #
1 # 2 #
1 # 2 # 3 #

Explanation

1. Numbers is a list containing the numbers 9, 18, 27, and 36.


2. The outer for loop iterates over each element in the list Numbers.
3. The inner loop iterates over the range from 1 to the remainder of Num divided by 8. For
example, if Num is 9, the range will be from 1 to 1 (9 % 8 = 1). If Num is 18, the range will
be from 1 to 2 (18 % 8 = 2), and so on. Then it prints the value of N, followed by a "#", and
ensures that the output is printed on the same line by setting end=" ".
4. After both loops, it prints an empty line, effectively adding a newline character to the
output.

Question 5(a)

Find the errors. State reasons.

t = (1, "a", 9.2)


t[0] = 6
Answer

t[0] = 6 will raise a TypeError as tuples are immutable (i.e., their elements cannot be changed
after creation).

Question 5(b)

Find the errors. State reasons.

t = [1, "a", 9.2]


t[0] = 6
Answer

There are no errors in this python code. Lists in python can contain elements of any type. As lists
are mutable so t[0] = 6 is also valid.

Question 5(c)

Find the errors. State reasons.

t = [1, "a", 9.2]


t[4] = 6
Answer

t[4] = 6 will raise an error as we are trying to change the value at index 4 but it is outside the
current range of the list t. As t has 3 elements so its indexes are 0, 1, 2 only.

Question 5(d)

Find the errors. State reasons.

t = 'hello'
t[0] = "H"
Answer

t[0] = "H" will raise an error because strings in python are immutable, meaning we cannot
change individual characters in a string after it has been created. Therefore, attempting to assign a
new value to t[0] will result in an error.

Question 5(e)

Find the errors. State reasons.

for Name in [Amar, Shveta, Parag]


IF Name[0] = 'S':
print(Name)
Answer

The errors in this code are:

1. In the list [Amar, Shveta, Parag] , each element should be enclosed in quotes
because they are strings.
2. The equality comparison operator is '==' instead of = for checking equality.
3. if statement should be lowercase.

Question 6

Assuming words is a valid list of words, the program below tries to print the list in reverse. Does it
have an error ? If so, why ? (Hint. There are two problems with the code.)

for i in range(len(words), 0, -1):


print(words[i], end=' ')
Answer

There are two issue in range(len(words), 0, -1) :

1. The start index len(words) is invalid for the list words as it will have indexes from 0
to len(words) - 1 .
2. The end index being 0 means that the last element of the list is missed as the list will be
iterated till index 1 only.

The corrected python code is :

for i in range(len(words)-1, -1, -1):


print(words[i], end=' ')

Question 7

What would be the output of following code if ntpl = ("Hello", "Nita", "How's", "life ?") ?

(a, b, c, d) = ntpl
print("a is:", a)
print("b is:", b)
print("c is:", c)
print("d is:", d)
ntpl = (a, b, c, d)
print(ntpl[0][0] + ntpl[1][1], ntpl[1])
Answer

Output

a is: Hello
b is: Nita
c is: How's
d is: life ?
Hi Nita

Explanation

ntpl is a tuple containing 4 elements. The statement (a, b, c, d) = ntpl unpacks the
tuple ntpl into the variables a, b, c, d. After that, the values of the variables are printed.
The statement ntpl = (a, b, c, d) forms a tuple with values of variables a, b, c, d and
assigns it to ntpl. As these variables were not modified, so effectively ntpl still contains the same

ntpl[0] ⇒ "Hello"
values as in the first statement.

∴ ntpl[0][0] ⇒ "H"

ntpl[1] ⇒ "Nita"
∴ ntpl[1][1] ⇒"i"

ntpl[0][0] and ntpl[1][1] concatenates to form "Hi". Thus ntpl[0][0]+ntpl[1]


[1], ntpl[1] will return "Hi Nita ".

Question 8

What will be the output of the following code ?

tuple_a = 'a', 'b'


tuple_b = ('a', 'b')
print (tuple_a == tuple_b)
Answer

Output

True

Explanation

Tuples can be declared with or without parentheses (parentheses are optional). Here, tuple_a is
declared without parentheses where as tuple_b is declared with parentheses but both are
identical. As both the tuples contain same values so the equality operator ( == ) returns true.

Question 9

What will be the output of the following code snippet ?

rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ",


"Country" : "USA"}
id1 = id(rec)
del rec
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ",
"Country" : "USA"}
id2 = id(rec)
print(id1 == id2)

1. True
2. False
3. 1
4. Exception

Answer

Output

True

Explanation

In the given python code snippet, id1 and id2 will point to two different objects in memory
as del rec deleted the original dictionary whose id is stored in id1 and created a new
dictionary with the same contents storing its id in id2. However, id1 == id2 will compare the
contents of the two dictionaries pointed to by id1 and id2. As contents of both the dictionaries
are same hence it returns True. If in this code we add another line print(id1 is
id2) then this line will print False as id1 and id2 point to two different dictionary objects in
memory.

Question 10

Write the output of the code given below :

my_dict = {"name" : "Aman", "age" : 26}


my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
Answer

Output

dict_items([('name', 'Aman'), ('age', 27), ('address',


'Delhi')])

Explanation

A dictionary my_dict with two key-value pairs, 'name': 'Aman' and 'age': 26 is initialized. Then
updates the value associated with the key 'age' to 27. Then adds a new key-value pair 'address':
'Delhi' to the dictionary my_dict. The items() method returns all of the items in the dictionary
as a sequence of (key, value) tuples. In this case, it will print [('name', 'Aman'), ('age', 27),
('address', 'Delhi')].

Question 11
Write a method in python to display the elements of list thrice if it is a number and display the
element terminated with '#' if it is not number.

For example, if the content of list is as follows :

List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']


The output should be
414141
DROND#
GIRIRAJ#
131313
ZAR#

Answer

def display(my_list):
for item in my_list:
if item.isdigit():
print(item * 3)
else:
print(item + '#')
display(my_list = eval(input("Enter the list :")))

Output

Enter the elements of the list separated by spaces:41 DROND


GIRIRAJ 13 ZARA
414141
DROND#
GIRIRAJ#
131313
ZARA#

Explanation

1. The code prompts the user to enter the elements of the list separated by spaces and
stores the input as a single string in the variable my_list.
2. Then splits the input string my_list into individual elements and stores them in a new list
called new_list.
3. Then for loop iterates over each element in the new_list.
4. The isdigit() method is used to check if all characters in the string are digits. If it's
true (i.e., if the element consists only of digits), then it prints the element concatenated with
itself three times. Otherwise, if the element contains non-digit characters, it prints the
element concatenated with the character '#'.

Question 12

Name the function/method required to

(i) check if a string contains only uppercase letters.

(ii) gives the total length of the list.

Answer
(i) isupper() method is used to check if a string contains only uppercase letters.

(ii) len() gives the total length of the list.

Question 13

What will be the output of the following code snippet ?

my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print(sum)
print(my_dict)
Answer

Output

30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}

Explanation

1. An empty dictionary named my_dict is initialized.


2. my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10,
my_dict[(1,2)] = 12 these lines assign values to the dictionary my_dict with
keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.
3. The for loop iterates over the keys of the dictionary my_dict. Inside the loop, the value
associated with each key k is added to the variable sum.
4. sum and my_dict are printed.

Type C: Programming Practice/Knowledge based


Questions

Question 1

Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after
the area code and the next three numbers. For example, 017-555-1212 is a legal input.
Display if the phone number entered is valid format or not and display if the phone number is valid
or not (i.e., contains just the digits and dash at specific places).

Solution

phNo = input("Enter the phone number: ")


length = len(phNo)
if length == 12 \
and phNo[3] == "-" \
and phNo[7] == "-" \
and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")

Output

Enter the phone number: 017-555-1212


Valid Phone Number

=====================================

Enter the phone number: 017-5A5-1212


Invalid Phone Number

Question 2

Write a program that should prompt the user to type some sentence(s) followed by "enter". It
should then print the original sentence(s) and the following statistics relating to the sentence(s):

 Number of words
 Number of characters (including white-space and punctuation)
 Percentage of characters that are alpha numeric

Hints

 Assume any consecutive sequence of non-blank characters in a word.

Solution

str = input("Enter a few sentences: ")


length = len(str)
spaceCount = 0
alnumCount = 0

for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1

alnumPercent = alnumCount / length * 100

print("Original Sentences:")
print(str)

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


print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)

Output
Enter a few sentences: Python was conceived in the late 1980s
by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in
the Netherlands. Its implementation began in December 1989.
Python 3.0 was released on 3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at
Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its
implementation began in December 1989. Python 3.0 was released
on 3 December 2008.
Number of words = 34
Number of characters = 205
Alphanumeric Percentage = 80.48780487804879

Question 3

Write a program that takes any two lists L and M of the same size and adds their elements
together to form a new list N whose elements are sums of the corresponding elements in L and M.
For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4, 6, 13].

Solution

print("Enter two lists of same size")


L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []

for i in range(len(L)):
N.append(L[i] + M[i])

print("List N:")
print(N)

Output

Enter two lists of same size


Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]

Question 4

Write a program that rotates the elements of a list so that the element at the first index moves to
the second index, the element in the second index moves to the third index, etc., and the element
in the last index moves to the first index.

Solution

l = eval(input("Enter the list: "))


print("Original List")
print(l)

l = l[-1:] + l[:-1]
print("Rotated List")
print(l)

Output

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


Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]

Question 5

Write a short python code segment that prints the longest word in a list of words.

Solution

my_list = eval(input("Enter the list : "))


longest_word = ""
max_length = 0

for word in my_list:


if len(word) > max_length:
max_length = len(word)
longest_word = word

print("Longest word:", longest_word)

Output

Enter the list : ['red', 'yellow', 'green', 'blue']


Longest word: yellow
Enter the list : ['lion', 'elephant', 'tiger', 'monkey',
'hippopotamus']
Longest word: hippopotamus

Question 6

Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.

Solution

a = []
for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
a.append(i)
print(a)

Output
[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, 54, 55, 57, 60, 63, 65, 66, 69,
70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]

Question 7

Define two variables first and second so that first = "Jimmy" and second = "Johny". Write a short
python code segment that swaps the values assigned to these two variables and prints the results.

Solution

first = "Jimmy"
second = "Johny"
temp = first
first = second
second = temp
print("first =", first)
print("second =", second)

Output

first = Johny
second = Jimmy

Question 8

Write a python program that creates a tuple storing first 9 terms of Fibonacci series.

Solution

lst = [0,1]
a = 0
b = 1
c = 0

for i in range(7):
c = a + b
a = b
b = c
lst.append(c)

tup = tuple(lst)

print("9 terms of Fibonacci series are:", tup)

Output

9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)

Question 9

Create a dictionary whose keys are month names and whose values are the number of days in the
corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell them how many days are in
the month.

(b) Print out all of the keys in alphabetical order.

(c) Print out all of the months with 31 days.

(d) Print out the (key-value) pairs sorted by the number of days in each month.

Solution

days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}

m = input("Enter name of month: ")

if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)

print("Months in alphabetical order are:",


sorted(days_in_months))

print("Months with 31 days:", end=" ")


for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")

day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()

month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])

sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
Output

Enter name of month: may


There are 31 days in may
Months in alphabetical order are: ['april', 'august',
'december', 'february', 'january', 'july', 'june', 'march',
'may', 'november', 'october', 'september']
Months with 31 days: january march may july august october
december
Months sorted by days: {'february': 28, 'april': 30, 'june':
30, 'november': 30, 'september': 30, 'august': 31, 'december':
31, 'january': 31, 'july': 31, 'march': 31, 'may': 31,
'october': 31}

Question 10

Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should
return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the
same key appears in both arguments, feel free to pick a value from either.

Solution

def addDict(dict1, dict2):


union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)

Output

Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}

Question 11

Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.

Solution

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


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

Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}


Sorted keys: ['a', 'c', 'f', 'r']

Question 12

Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a
list.

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]

LESSON. 3 WORKING WITH FUNCTION

Checkpoint 3.1

Question 1

If return statement is not used inside the function, the function will
return:

1. 0
2. None object
3. an arbitrary integer
4. Error! Functions in Python must have a return statement.

Answer
None object
Reason — The default return value for a function that does not return
any value explicitly is None.
Question 2

Which of the following keywords marks the beginning of the function


block?

1. func
2. define
3. def
4. function

Answer
def
Reason — The function in Python is defined as per following syntax :
def function_name(parameters):
statements

According to this format, function definition begins with keyword def.

Question 3

What is the area of memory called, which stores the parameters and
local variables of a function call ?

1. a heap
2. storage area
3. a stack
4. an array

Answer
a stack
Reason — A stack is the area of memory, which stores the parameters
and local variables of a function call.

Question 4

Find the errors in following function definitions :


1. def main()
2. print ("hello")

3. def func2():
4. print(2 + 3)

5. def compute():
6. print (x * x)

7. square (a)
8. return a * a

Answer

1. Colon is missing at the end of function header.


2. There is no error.
3. The variable x is not defined.
4. def keyword at the beginning and colon at the end of function
header are missing.

The corrected function definitions are:


1. def main():
2. print("hello")
3. def func2():
4. print(2 + 3)

5. def compute(x):
6. print (x * x)

7. def square(a):
8. return a * a

ype A: Short Answer Questions/Conceptual


Questions

Question 1

A program having multiple functions is considered better designed than a program without any
functions. Why ?

Answer

A program having multiple functions is considered better designed than a program without any
functions because

1. It makes program handling easier as only a small part of the program is dealt with at a
time, thereby avoiding ambiguity.
2. It reduces program size.
3. Functions make a program more readable and understandable to a programmer thereby
making program management much easier.

Question 2

What all information does a function header give you about the function ?

Answer
Function header is the first line of function definition that begins with keyword def and ends with a
colon (:), specifies the name of the function and its parameters.

Question 3

What do you understand by flow of execution ?

Answer

Flow of execution refers to the order in which statements are executed during a program run.

Question 4

What are arguments ? What are parameters ? How are these two terms different yet related ?
Give example.

Answer

Arguments — The values being passed through a function-call statement are called arguments.

Parameters — The values received in the function definition/header are called parameters.

Arguments appear in function call statement whereas parameters appear in function header. The
two terms are related because the values passed through arguments while calling a function are
received by parameters in the function definition.

For example :

def multiply(a, b):


print(a * b)
multiply(3, 4)
Here, a and b are parameters while 3, 4 are arguments.

Question 5

What is the utility of : (i) default arguments, (ii) keyword arguments ?

Answer

(i) Default arguments — Default arguments are useful in case a matching argument is not passed
in the function call statement. They give flexibility to specify the default value for a parameter so
that it can be skipped in the function call, if needed. However, still we cannot change the order of
the arguments in the function call.

(ii) Keyword arguments — Keyword arguments are useful when you want to specify arguments
by their parameter names during a function call. This allows us to pass arguments in any order, as
long as we specify the parameter names when calling the function. It also makes the function call
more readable and self-explanatory.

Question 6

Explain with a code example the usage of default arguments and keyword arguments.

Answer

Default arguments — Default arguments are used to provide a default value to a function
parameter if no argument is provided during the function call.
For example :

def greet(name, message="Hello"):


print(message, name)

greet("Alice")
greet("Bob", "Hi there")

Output

Hello Alice
Hi there Bob
In this example, the message parameter has a default value of "Hello". If no message argument is
provided during the function call, the default value is used.

Keyword arguments — Keyword arguments allow us to specify arguments by their parameter


names during a function call, irrespective of their position.

def person(name, age, city):


print(name, "is", age, "years old and lives in", city)

person(age=25, name="Alice", city="New York")


person(city="London", name="Bob", age=30)

Output

Alice is 25 years old and lives in New York


Bob is 30 years old and lives in London
In this example, the arguments are provided in a different order compared to the function
definition. Keyword arguments specify which parameter each argument corresponds to, making
the code more readable and self-explanatory.

Both default arguments and keyword arguments provide flexibility and improve the readability of
code, especially in functions with multiple parameters or when calling functions with optional
arguments.

Question 7

Describe the different styles of functions in Python using appropriate examples.

Answer

The different styles of functions in Python are as follows :

1. Built-in functions — These are pre-defined functions and are always available for use.
For example:

2. name = input("Enter your name: ")


3. name_length = len(name)
print("Length of your name:", name_length)
In the above example, print(), len(), input() etc. are built-in functions.

4. User defined functions — These are defined by programmer. For example:

5. def calculate_area(length, width):


6. area = length * width
7. return area
8. length = 5
9. width = 3
10. result = calculate_area(length, width)
print("Area of the rectangle:", result)
In the above example, calculate_area is a user defined function.

11. Functions defined in modules — These functions are pre-defined in particular modules
and can only be used when corresponding module is imported. For example:

12. import math


13. num = 16
14. square_root = math.sqrt(num)
print("Square root of", num, ":", square_root)
In the above example, sqrt is a function defined in math module.

Question 8

Differentiate between fruitful functions and non-fruitful functions.

Answer

Fruitful functions Non-fruitful functions

Functions returning some value are called Functions that does not return any value are called as non-
as fruitful functions. fruitful functions.

They are also called as non-void functions. They are also called as void functions.

They have return statements in the They may or may not have a return statement, but if they do,
syntax : return<value>. it typically appears as per syntax : return.
Fruitful functions return some computed Non-fruitful functions return legal empty value of Python,
result in terms of a value. which is None, to their caller.

Question 9

Can a function return multiple values ? How ?

Answer

Yes, a function can return multiple values. To return multiple values from a function, we have to
ensure following things :

1. The return statement inside a function body should be of the form :

return
<value1/variable1/expression1>,<value2/variable2/expression2>,.
...
2. The function call statement should receive or use the returned values in one of the following
ways :

(a) Either receive the returned values in form a tuple variable.

(b) Or we can directly unpack the received values of tuple by specifying the same number of
variables on the left-hand side of the assignment in function call.

Question 10

What is scope ? What is the scope resolving rule of Python ?

Answer

Scope refers to part(s) of program within which a name is legal and accessible. When we access a
variable from within a program or function, Python follows name resolution rule, also known as
LEGB rule. When Python encounters a name (variable or function), it first searches the local scope
(L), then the enclosing scope (E), then the global scope (G), and finally the built-in scope (B).

Question 11

What is the difference between local and global variable ?

Answer

Local variable Global variable

A local variable is a variable defined within a A global variable is a variable defined in the 'main'
function. program.

They are only accessible within the block in which They are accessible from anywhere within the
they are defined. program, including inside functions.

These variables have local scope. These variables have global scope.

The lifetime of a local variable is limited to the block Global variables persist throughout the entire
of code in which it is defined. Once the execution execution of the program. They are created when
exits that block, the local variable is destroyed, and the program starts and are only destroyed when the
its memory is released. program terminates.

Question 12

When is global statement used ? Why is its use not recommended ?

Answer

If we want to assign some value to the global variable without creating any local variable then
global statement is used. It is not recommended because once a variable is declared global in a
function, we cannot undo the statement. That is, after a global statement, the function will always
refer to the global variable and local variable cannot be created of the same name. Also, by using
global statement, programmers tend to lose control over variables and their scopes.
Question 13

Write the term suitable for following descriptions :

(a) A name inside the parentheses of a function header that can receive a value.

(b) An argument passed to a specific parameter using the parameter name.

(c) A value passed to a function parameter.

(d) A value assigned to a parameter name in the function header.

(e) A value assigned to a parameter name in the function call.

(f) A name defined outside all function definitions.

(g) A variable created inside a function body.

Answer

(a) Parameter

(b) Keyword argument

(c) Argument

(d) Default value

(e) Keyword argument

(f) Global variable

(g) Local variable

Question 14

What do you understand by local and global scope of variables ? How can you access a global
variable inside the function, if function has a variable with same name.

Answer

Local scope — Variables defined within a specific block of code, such as a function or a loop,
have local scope. They are only accessible within the block in which they are defined.

Global scope — Variables defined outside of any specific block of code, typically at the top level
of a program or module, have global scope. They are accessible from anywhere within the
program, including inside functions.

To access a global variable inside a function, even if the function has a variable with the same
name, we can use the global keyword to declare that we want to use the global variable instead
of creating a new local variable. The syntax is :
global<variable name>
For example:

def state1():
global tigers
tigers = 15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)
In the above example, tigers is a global variable. To use it inside the function state1 we have
used global keyword to declare that we want to use the global variable instead of creating a new
local variable.
Type B: Application Based Questions

Question 1(a)

What are the errors in following codes ? Correct the code and predict output :

total = 0;
def sum(arg1, arg2):
total = arg1 + arg2;
print("Total :", total)
return total;
sum(10, 20);
print("Total :", total)
Answer

total = 0
def sum(arg1, arg2):
total = arg1 + arg2
print("Total :", total)
return total
sum(10, 20)
print("Total :", total)

Output

Total : 30
Total : 0

Explanation

1. There is an indentation error in second line.


2. The return statement should be indented inside function and it should not end with
semicolon.
3. Function call should not end with semicolon.

Question 1(b)

What are the errors in following codes ? Correct the code and predict output :

def Tot(Number) #Method to find Total


Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])
Answer

def Tot(Number): #Method to find Total


Sum = 0
for C in range(1, Number + 1):
Sum += C
return Sum
print(Tot(3)) #Function Calls
print(Tot(6))

Output

6
21

Explanation

1. There should be a colon (:) at the end of the function definition line to indicate the start of
the function block.
2. Python's built-in function for generating sequences is range(), not Range().
3. Python keywords like return should be in lowercase.
4. When calling a function in python, the arguments passed to the function should be
enclosed inside parentheses () not square brackets [].

Question 2

Find and write the output of the following python code :

def Call(P = 40, Q = 20):


P = P + Q
Q = P - Q
print(P, '@', Q)
return P
R = 200
S = 100
R = Call(R, S)
print(R, '@', S)
S = Call(S)
print(R, '@', S)
Answer

Output

300 @ 200
300 @ 100
120 @ 100
300 @ 120

Explanation
1. Function Call is defined with two parameters P and Q with default values 40 and 20
respectively.
2. Inside the function Call, P is reassigned to the sum of its original value P and the value
of Q.
3. Q is reassigned to the difference between the new value of P and the original value of Q.
4. Prints the current values of P and Q separated by @.
5. The function returns the final value of P.
6. Two variables R and S are initialized with values 200 and 100 respectively.
7. The function Call is called with arguments R and S, which are 200 and 100 respectively.
Inside the function, P becomes 200 + 100 = 300 and Q becomes 300 - 100 = 200. So, 300
and 200 are printed. The function returns 300, which is then assigned to R.
Therefore, R becomes 300.
8. S = Call(S) — The function Call is called with only one argument S, which is 100. Since
the default value of Q is 20, P becomes 100 + 20 = 120, and Q becomes 120 - 20 = 100.
So, 120 and 100 are printed. The function returns 120, which is then assigned to S.
Therefore, S becomes 120.

Question 3

Consider the following code and write the flow of execution for this. Line numbers have been given
for your reference.

1. def power(b, p):


2. y = b ** p
3. return y
4.
5. def calcSquare(x):
6. a = power(x, 2)
7. return a
8.
9. n = 5
10. result = calcSquare(n)
11. print(result)
Answer

The flow of execution for the above program is as follows :

1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11

Explanation

Line 1 is executed and determined that it is a function header, so entire function-body (i.e., lines 2
and 3) is ignored. Line 5 is executed and determined that it is a function header, so entire function-
body (i.e., lines 6 and 7) is ignored. Lines 9 and 10 are executed, line 10 has a function call, so
control jumps to function header (line 5) and then to first line of function-body, i.e., line 6, it has a
function call , so control jumps to function header (line 1) and then to first line of function-body, i.e,
line 2. Function returns after line 3 to line 6 and then returns after line 7 to line containing function
call statement i.e, line 10 and then to line 11.

Question 4

What will the following function return ?

def addEm(x, y, z):


print(x + y + z)
Answer

The function addEm will return None. The provided function addEm takes three parameters x, y,
and z, calculates their sum, and then prints the result. However, it doesn't explicitly return any
value. In python, when a function doesn't have a return statement, it implicitly returns None.
Therefore, the function addEm will return None.

Question 5

What will the following function print when called ?

def addEm(x, y, z):


return x + y + z
print(x + y + z)
Answer

The function addEm prints nothing when called.

Explanation

1. The function addEm(x, y, z) takes three parameters x, y, and z.


2. It returns the sum of x, y, and z.
3. Since the return statement is encountered first, the function exits immediately after
returning the sum. The print statement after the return statement is never executed.
Therefore, it prints nothing.

Question 6(i)

What will be the output of following program ?

num = 1
def myfunc():
return num
print(num)
print(myfunc())
print(num)
Answer

Output

1
1
1

Explanation

The code initializes a global variable num with 1. myfunc just returns this global variable. Hence,
all the three print statements print 1.

Question 6(ii)

What will be the output of following program ?

num = 1
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer

Output

1
10
1

Explanation

1. num = 1 — This line assigns the value 1 to the global variable num.
2. def myfunc() — This line defines a function named myfunc.
3. print(num) — This line prints the value of the global variable num, which is 1.
4. print(myfunc()) — This line calls the myfunc function. Inside myfunc function, num =
10 defines a local variable num and assigns it the value of 10 which is then returned by the
function. It is important to note that the value of global variable num is still 1
as num of myfunc is local to it and different from global variable num.
5. print(num) — This line prints the value of the global variable num, which is still 1.

Question 6(iii)

What will be the output of following program ?

num = 1
def myfunc():
global num
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer

Output

1
10
10

Explanation

1. num = 1 — This line assigns the value 1 to the global variable num.
2. def myfunc() — This line defines a function named myfunc.
3. print(num) — This line prints the value of the global variable num, which is 1.
4. print(myfunc()) — This line calls the myfunc function. Inside the myfunc function, the
value 10 is assigned to the global variable num. Because of the global keyword used
earlier, this assignment modifies the value of the global variable num to 10. The function
then returns 10.
5. print(num) — This line prints the value of the global variable num again, which is still 1.

Question 6(iv)

What will be the output of following program ?

def display():
print("Hello", end='')
display()
print("there!")
Answer

Output

Hellothere!

Explanation

The function display prints "Hello" without a newline due to the end='' parameter. When called, it
prints "Hello". Outside the function, "there!" is printed on the same line due to the absence of a
newline.

Question 7

Predict the output of the following code :

a = 10
y = 5
def myfunc():
y = a
a = 2
print("y =", y, "a =", a)
print("a + y =", a + y)
return a + y
print("y =", y, "a =", a)
print(myfunc())
print("y =", y, "a =", a)
Answer

The code raises an error when executed.

Explanation

In the provided code, the global variables a and y are initialized to 10 and 5, respectively. Inside
the myfunc function, the line a = 2 suggests that a is a local variable of myfunc. But the line
before it, y = a is trying to assign the value of local variable a to local variable y even before local
variable a is defined. Therefore, this code raises an UnboundLocalError.

Question 8

What is wrong with the following function definition ?


def addEm(x, y, z):
return x + y + z
print("the answer is", x + y + z)
Answer

In the above function definition, the line print("the answer is", x + y + z) is placed after
the return statement. In python, once a return statement is encountered, the function exits
immediately, and any subsequent code in the function is not executed. Therefore, the print
statement will never be executed.

Question 9

Write a function namely fun that takes no parameters and always returns None.

Answer

def fun():
return

Explanation

def fun():
return
r = fun()
print(r)
The function fun() returns None. When called, its return value is assigned to r, which
holds None. Then print(r) outputs None.

Question 10

Consider the code below and answer the questions that follow :

def multiply(number1, number2):


answer = number1 * number2
print(number1, 'times', number2, '=', answer)
return(answer)
output = multiply(5, 5)
(i) When the code above is executed, what prints out ?

(ii) What is variable output equal to after the code is executed ?

Answer

(i) When the code above is executed, it prints:

5 times 5 = 25
(ii) After the code is executed, the variable output is equal to 25. This is because the function
multiply returns the result of multiplying 5 and 5, which is then assigned to the variable output.

Question 11

Consider the code below and answer the questions that follow :

def multiply(number1, number2):


answer = number1 * number2
return(answer)
print(number1, 'times', number2, '=', answer)
output = multiply(5, 5)
(i) When the code above is executed, what gets printed ?

(ii) What is variable output equal to after the code is executed ?

Answer

(i) When the code above is executed, it will not print anything because the print statement after the
return statement won't execute. Therefore, the function exits immediately after encountering the
return statement.

(ii) After the code is executed, the variable output is equal to 25. This is because the function
multiply returns the result of multiplying 5 and 5, which is then assigned to the variable output.

Question 12(a)

Find the errors in code given below :

def minus(total, decrement)


output = total - decrement
print(output)
return (output)
Answer

The errors in the code are:

def minus(total, decrement) # Error 1


output = total - decrement
print(output)
return (output)

1. There should be a colon at the end of the function definition line.

The corrected code is given below:

def minus(total, decrement):


output = total - decrement
print(output)
return (output)

Question 12(b)

Find the errors in code given below :

define check()
N = input ('Enter N: ')
i = 3
answer = 1 + i ** 4 / N
Return answer
Answer
The errors in the code are:

define check() #Error 1


N = input ('Enter N: ') #Error 2
i = 3
answer = 1 + i ** 4 / N
Return answer #Error 3

1. The function definition lacks a colon at the end.


2. The 'input' function returns a string. To perform arithmetic operations with N, it needs to be
converted to a numeric type, such as an integer or a float.
3. The return statement should be in lowercase.

The corrected code is given below:

def check():
N = int(input('Enter N:'))
i = 3
answer = 1 + i ** 4 / N
return answer

Question 12(c)

Find the errors in code given below :

def alpha (n, string = 'xyz', k = 10) :


return beta(string)
return n

def beta (string)


return string == str(n)

print(alpha("Valentine's Day"):)
print(beta(string = 'true'))
print(alpha(n = 5, "Good-bye"):)
Answer

The errors in the code are:

def alpha (n, string = 'xyz', k = 10) :


return beta(string)
return n #Error 1

def beta (string) #Error 2


return string == str(n)

print(alpha("Valentine's Day"):) #Error 3


print(beta(string = 'true')) #Error 4
print(alpha(n = 5, "Good-bye"):) #Error 5

1. The second return statement in the alpha function (return n) is unreachable because the
first return statement return beta(string) exits the function.
2. The function definition lacks colon at the end. The variable n in the beta function is not
defined. It's an argument to alpha, but it's not passed to beta explicitly. To
access n within beta, we need to either pass it as an argument or define it as a global
variable.
3. There should not be colon at the end in the function call.
4. In the function call beta(string = 'true'), there should be argument for parameter n.
5. In the function call alpha(n = 5, "Good-bye"), the argument "Good-bye" lacks a
keyword. It should be string = "Good-bye".

The corrected code is given below:

def alpha(n, string='xyz', k=10):


return beta(string, n)

def beta(string, n):


return string == str(n)

print(alpha("Valentine's Day"))
print(beta(string='true', n=10))
print(alpha(n=5, string="Good-bye"))

Question 13

Draw the entire environment, including all user-defined variables at the time line 10 is being
executed.

1. def sum(a, b, c, d):


2. result = 0
3. result = result + a + b + c + d
4. return result
5.
6. def length():
7. return 4
8.
9. def mean(a, b, c, d):
10. return float(sum(a, b, c, d))/length()
11.
12. print(sum(a, b, c, d), length(), mean(a, b, c, d))
Answer

The environment when the line 10 is being executed is shown below :


Question 14

Draw flow of execution for the above program.

Answer

The flow of execution for the above program is as follows :

1 → 6 → 9 → 12 → 1 → 2 → 3 → 4 → 6 → 7 → 9 → 10 → 12

Line 1 is executed and determined that it is a function header, so entire function-body (i.e, lines 2,
3, 4) is ignored.Then line 6 is executed and determined that it is a function header, so entire
function-body (i.e, line 7) is ignored, Line 9 is executed and determined that it is a function header,
so entire function-body (i.e, line 10) is ignored. Then line 12 is executed and it has a function calls,
so control jumps to the function header (line 1) and then first line of function-body, i.e, line 2,
function returns after line 4 to function call line (line 12) and then control jumps to line 6, it is a
function header and then first line of function-body, i.e., line 7, function returns after line 7 to
function call line (line 12) and then control jumps to line 9, it is a function header and then first line
of function-body, i.e., line 10, function returns after line 10 to function call line 12.

Question 15

Find and write the output of the following python code :

a = 10
def call():
global a
a = 15
b = 20
print(a)
call()
Answer

Output

15

Explanation

1. a = 10 — This line assigns the value 10 to the global variable a.


2. def call() — This line defines a function named call.
3. a = 15 — Inside the call function, this line assigns the value 15 to the global variable a.
As global keyword is used earlier, this assignment modifies the value of the global
variable a.
4. b = 20 — Inside the call function, this line assigns the value 20 to a local variable b.
5. print(a) — This line prints the value of the global variable a, which is 15. This is
because we've modified the global variable a inside the call function.

Question 16

In the following code, which variables are in the same scope ?

def func1():
a = 1
b = 2

def func2():
c = 3
d = 4
e = 5
Answer

In the code, variables a and b are in the same scope because they are defined within the same
function func1(). Similarly, variables c and d are in the same scope because they are defined
within the same function func2(). e being a global variable is not in the same scope.

Question 17

Write a program with a function that takes an integer and prints the number that follows after it.
Call the function with these arguments :

4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2

Answer

1. def print_number(number):
2. next_number = number + 1
3. print("The number following", number, "is", next_number)
4. print_number(4)
5. print_number(6)
6. print_number(8)
7. print_number(2 + 1)
8. print_number(4 - 3 * 2)
9. print_number(- 3 - 2)

Output

The print_number following 4 is 5


The print_number following 6 is 7
The print_number following 8 is 9
The print_number following 3 is 4
The print_number following -2 is -1
The print_number following -5 is -4

Explanation

1. def print_number(number) — This line defines a function named print_number that


takes one argument number.
2. next_number = number + 1 — Inside the print_number function, this line calculates
the next number after the input number by adding 1 to it and assigns the result to the
variable next_number.
3. print("The number following", number, "is", next_number) — Inside
the print_number function, this line prints a message stating the number and its following
number.
4. Then the print_number function is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2),
((-3-2) = -5) as arguments.

Question 18

Write a program with non-void version of above function and then write flow of execution for both
the programs.

Answer

The non-void version of above code is as shown below :

1. def print_number(number):
2. next_number = number + 1
3. return next_number
4. print(print_number(4))
5. print(print_number(6))
6. print(print_number(8))
7. print(print_number(2 + 1))
8. print(print_number(4 - 3 * 2))
9. print(print_number(-3 - 2))

Output

5
7
9
4
-1
-4

Explanation
1. def print_number(number) — This line defines a function named print_number that
takes one argument number.
2. next_number = number + 1 — Inside the print_number function, this line calculates
the next number after the input number by adding 1 to it and assigns the result to the
variable next_number.
3. return next_number — Inside the print_number function, this line
returns next_number.
4. Then the print_number function is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2),
((-3-2) = -5) as arguments.
The flow of execution for the above program with non-void version is as follows :

1→4→1→2→3→4→5→1→2→3→5→6→1→2→3→6→7→1→2→3→7
→8→1→2→3→8→9→1→2→3→9

Line 1 is executed and determined that it is a function header, so entire function-body (i.e., line 2
and 3) is ignored. Then line 4 is executed and it has function call, so control jumps to the function
header (line 1) and then to first line of function-body, i.e., line 2, function returns after line 3 to line
containing function call statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so they
repeat the above steps.

The flow of execution for the void version program is as follows :

1→4→1→2→3→4→5→1→2→3→5→6→1→2→3→6→7→1→2→3→7
→8→1→2→3→8→9→1→2→3→9

Line 1 is executed and determined that it is a function header, so entire function-body (i.e., line 2
and 3) is ignored. Then line 4 is executed and it has function call, so control jumps to the function
header (line 1) and then to first line of function-body, i.e., line 2, function returns after line 3 to line
containing function call statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so they
repeat the above steps.

Question 19(i)

What is the output of following code fragments ?

def increment(n):
n.append([4])
return n
L = [1, 2, 3]
M = increment(L)
print(L, M)
Answer

Output

[1, 2, 3, [4]] [1, 2, 3, [4]]

Explanation

In the code, the function increment appends [4] to list n, modifying it in place. When L = [1, 2,
3], calling increment(L) changes L to [1, 2, 3, [4]]. Variable M receives the same modified list [1,
2, 3, [4]], representing L. Thus, printing L and M results in [1, 2, 3, [4]], confirming they reference
the same list. Therefore, modifications made to list inside a function affect the original list passed
to the function.

Question 19(ii)
What is the output of following code fragments ?

def increment(n):
n.append([49])
return n[0], n[1], n[2], n[3]
L = [23, 35, 47]
m1, m2, m3, m4 = increment(L)
print(L)
print(m1, m2, m3, m4)
print(L[3] == m4)
Answer

Output

[23, 35, 47, [49]]


23 35 47 [49]
True

Explanation

The function increment appends [49] to list n and returns its first four elements individually.
When L = [23, 35, 47], calling increment(L) modifies L to [23, 35, 47, [49]]. Variables m1,
m2, m3, and m4 are assigned the same list [23, 35, 47, [49]], representing the original list L.
Thus, printing L and m1, m2, m3, m4 yields [23, 35, 47, [49]]. The expression L[3] == m4
evaluates to True, indicating that the fourth element of L is the same as m4.

Question 20

What will be the output of the following Python code ?

V = 25
def Fun(Ch):
V = 50
print(V, end = Ch)
V *= 2
print(V, end = Ch)
print(V, end = "*")
Fun("!")
print(V)

1. 25*50!100!25
2. 50*100!100!100
3. 25*50!100!100
4. Error

Answer

25*50!100!25

Explanation

1. V = 25 — initializes global variable V to 25.


2. print(V, end = "*") — Prints the global variable V (25) followed by an asterisk without
a newline.
3. Fun("!") — Calls the function Fun with the argument "!".
4. Inside function Fun, V = 50 initializes a local variable V within the function with the value
50. This variable is different from the global variable V that has the value 25.
5. print(V, end = Ch) — Prints the local variable V (50) followed by the character passed
as an argument to the function, which is "!".
6. V *= 2 — Multiplies the local variable V (50) by 2, making it 100.
7. print(V, end = Ch) — Prints the updated local variable V (100) followed by the
character "!".
8. The function Fun returns and the line print(V) is executed. It prints the global
variable V without any newline character. The global variable V remains unchanged (25).

Type C: Programming Practice/Knowledge based


Questions

Question 1

Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns
the amount converted to rupees. Create the function in both void and non-void forms.

Solution

def convert_dollars_to_rupees(amount_in_dollars,
conversion_rate):
amount_in_rupees = amount_in_dollars * conversion_rate
return amount_in_rupees

def convert_dollars_to_rupees_void(amount_in_dollars,
conversion_rate):
amount_in_rupees = amount_in_dollars * conversion_rate
print("Amount in rupees:", amount_in_rupees)

amount = float(input("Enter amount in dollars "))


conversion_rate = float(input("Enter conversion rate "))

# Non-void function call


converted_amount = convert_dollars_to_rupees(amount,
conversion_rate)
print("Converted amount (non-void function):",
converted_amount)

# Void function call


convert_dollars_to_rupees_void(amount, conversion_rate)

Output

Enter amount in dollars 50


Enter conversion rate 74.5
Converted amount (non-void function): 3725.0
Amount in rupees: 3725.0

Enter amount in dollars 100


Enter conversion rate 75
Converted amount (non-void function): 7500.0
Amount in rupees: 7500.0

Question 2

Write a function to calculate volume of a box with appropriate default values for its parameters.
Your function should have the following input parameters :

(a) length of box ;

(b) width of box ;

(c) height of box.

Test it by writing complete program to invoke it.

Solution

def calculate_volume(length = 5, width = 3, height = 2):


return length * width * height

default_volume = calculate_volume()
print("Volume of the box with default values:", default_volume)

v = calculate_volume(10, 7, 15)
print("Volume of the box with default values:", v)

a = calculate_volume(length = 23, height = 6)


print("Volume of the box with default values:", a)

b = calculate_volume(width = 19)
print("Volume of the box with default values:", b)

Output

Volume of the box with default values: 30


Volume of the box with default values: 1050
Volume of the box with default values: 414
Volume of the box with default values: 190

Question 3

Write a program to have following functions :

(i) a function that takes a number as argument and calculates cube for it. The function does not
return a value. If there is no value passed to the function in function call, the function should
calculate cube of 2.

(ii) a function that takes two char arguments and returns True if both the arguments are equal
otherwise False.

Test both these functions by giving appropriate function call statements.

Solution
# Function to calculate cube of a number
def calculate_cube(number = 2):
cube = number ** 3
print("Cube of", number, "is", cube)

# Function to check if two characters are equal


def check_equal_chars(char1, char2):
return char1 == char2

calculate_cube(3)
calculate_cube()

char1 = 'a'
char2 = 'b'
print("Characters are equal:", check_equal_chars(char1, char1))
print("Characters are equal:", check_equal_chars(char1, char2))

Output

Cube of 3 is 27
Cube of 2 is 8
Characters are equal: True
Characters are equal: False

Question 4

Write a function that receives two numbers and generates a random number from that range.
Using this function, the main program should be able to print three numbers randomly.

Solution

import random

def generate_random_number(num1, num2):


low = min(num1, num2)
high = max(num1, num2)
return random.randint(low, high)

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

for i in range(3):
random_num = generate_random_number(num1, num2)
print("Random number between", num1, "and", num2, ":",
random_num)

Output

Enter the first number: 2


Enter the second number: 78
Random number between 2 and 78 : 77
Random number between 2 and 78 : 43
Random number between 2 and 78 : 52
Enter the first number: 100
Enter the second number: 599
Random number between 100 and 599 : 187
Random number between 100 and 599 : 404
Random number between 100 and 599 : 451

Question 5

Write a function that receives two string arguments and checks whether they are same-length
strings (returns True in this case otherwise False).

Solution

def same_length_strings(str1, str2):


return len(str1) == len(str2)

s1 = "hello"
s2 = "world"
s3 = "python"

print(same_length_strings(s1, s2))
print(same_length_strings(s1, s3))

Output

True
False

Question 6

Write a function namely nthRoot( ) that receives two parameters x and n and returns nth root of x
i.e., x^(1/n).
The default value of n is 2.

Solution

def nthRoot(x, n = 2):


return x ** (1/n)

x = int(input("Enter the value of x:"))


n = int(input("Enter the value of n:"))

result = nthRoot(x, n)
print("The", n, "th root of", x, "is:", result)

default_result = nthRoot(x)
print("The square root of", x, "is:", default_result)

Output

Enter the value of x:36


Enter the value of n:6
The 6 th root of 36 is: 1.8171205928321397
The square root of 36 is: 6.0

Question 7

Write a function that takes a number n and then returns a randomly generated number having
exactly n digits (not starting with zero) e.g., if n is 2 then function can randomly return a number
10-99 but 07, 02 etc. are not valid two digit numbers.

Solution

import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)

n = int(input("Enter the value of n:"))


random_number = generate_number(n)
print("Random number:", random_number)

Output

Enter the value of n:2


Random number: 10

Enter the value of n:2


Random number: 50

Enter the value of n:3


Random number: 899

Enter the value of n:4


Random number: 1204

Question 8

Write a function that takes two numbers and returns the number that has minimum one's digit.

[For example, if numbers passed are 491 and 278, then the function will return 491 because it has
got minimum one's digit out of two given numbers (491's 1 is < 278's 8)].

Solution

def min_ones_digit(num1, num2):


ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
result = min_ones_digit(num1, num2)
print("Number with minimum one's digit:", result)

Output

Enter first number:491


Enter second number:278
Number with minimum one's digit: 491

Enter first number:543


Enter second number:765
Number with minimum one's digit: 543

Question 9

Write a program that generates a series using a function which takes first and last values of the
series and then generates four terms that are equidistant e.g., if two numbers passed are 1 and 7
then function returns 1 3 5 7.

Solution

def generate_series(first, last):


step = (last - first) // 3
series = [first, first + step, first + 2 * step, last]
return series

first_value = int(input("Enter first value:"))


last_value = int(input("Enter last value:"))
result_series = generate_series(first_value, last_value)
print("Generated Series:", result_series)

Output

Enter first value:1


Enter last value:7
Generated Series: [1, 3, 5, 7]

Enter first value:10


Enter last value:25
Generated Series: [10, 15, 20, 25]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy