0% found this document useful (0 votes)
12 views93 pages

Python Error Finding Questions

The document contains a series of Python code snippets with errors, asking the reader to identify and correct them. It also includes questions about lists in Python, their properties, and examples of list operations. The document serves as a practice guide for learning Python programming, particularly focusing on lists and error handling.
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)
12 views93 pages

Python Error Finding Questions

The document contains a series of Python code snippets with errors, asking the reader to identify and correct them. It also includes questions about lists in Python, their properties, and examples of list operations. The document serves as a practice guide for learning Python programming, particularly focusing on lists and error handling.
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

REFERENCE : [Link]

com/important-practice-questions-of-list-in-python/

Python Error Finding Questions


1. Find error(s) in the following code(if any) and rewrite code and underline each correction:
Ans.
x= int(“Enter value of x:”) x= int(input(“Enter value of x:”))
for in range [0,10]: for y in range (0,10):
if x=y if x==y:
print("They are equal") print("They are equal")
else: else:
Print( "They are unequal") print( "They are unequal")

2. Find error(s) in the following code(if any) and rewrite code and underline each correction.
Ans.
a, b = 0 a= b = 0
if (a = b) if (a == b):
a +b = c c=a+b
print( z) print( c)

3. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
A = int(input("Enter any number:")) Ans.
Ar = 0 A = int(input("Enter any number:"))
for x in range(0,A,2) Ar = 0
Ar+=x for x in range(0,A,2):
if x%2=0: Ar+=x
Print (x*10) if x%2==0:
Else: print (x+2)
print (C) else:
print (Ar) print (x)
print (Ar)
4. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
fee=250
0=i
while fee=<2000:
if fee<=750:
print (fee)
1

fee =+ 250
Page

else:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


print( "fee"*i) Ans.
i=i+1 fee=250
fee=Fee+250 i=0
while fee<=2000:
if fee<=750:
print (fee)
fee += 250
else:
print( "fee"*i)
i=i+1
fee=fee+250
5. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
Ans.
10 = step step = 10
for e in the range(0 , step): for e in range(0 , step):
If e%2==0: if e%2==0:
print(e + 1) print(e + 1)
else: else:
print(e - 1 print(e - 1)
6. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
Ans.
str = "Welcome to my Blog str = "Welcome to my Blog"
for S in range[3,9] for S in range(3,9):
Print (str(S)) print (str[S])
7. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
Ans:
For i in Range(10): for i in range(10):
if(i==5) if(i==5):
break: break
else: else:
print(i) print(i)
continue continue
8. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
a = input("Enter any number")
2

if a%2=0:
Page

print("Even number)
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Else Ans.
print("Odd number") a = int(input("Enter any number"))
if a%2==0:
print("Even number")
else:
print("Odd number")
9. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.

a = int(Input("Enter any number")) Ans.


b = int(input("Enter any number")) a = int(input("Enter any number"))
if a=>b: b = int(input("Enter any number"))
print("First number is greater")) if a>=b:
else: print("First number is greater")
Print("Second number is greater") else:
print("Second number is greater")
10. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
a = int{input("Enter any number")} Ans.
for i IN range(1:11): a = int(input("Enter any number"))
print(a," * " , i , " = ", a*i) for i in range(1,11):
print(a," * " , i , " = ", a*i)

11. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code
def sum(c) Ans:
s=0 def sum(c):
for i in Range(1, c+1) s=0
s=s+i for i in range(1, c+1):
return s s=s+i
print(sum(5) return s
print(sum(5))
12. Rectify the errors in the following statements:
1. Print("Anuj") Ans:
2. For i in range(2,4): 1. print("Anuj")
3. for i in Range(3,9): 2. for i in range(2,4):
4. def title( ) 3. for i in range(3,9):
5. if i =< 5 4. def title( ):
3

5. if i <= 5
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


13. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code
N=int(input("Enter any Number:")) Ans:
S=0 N=int(input("Enter any Number:"))
for i in range(1,N,2) S=0
s += 1 for i in range(1,N,2):
if i%2=0: S += 1
print("i" * 2) if i%2==0:
else: print("i" * 2)
print("i" * 3) else:
print[S] print("i" * 3)
print(S)
14. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
L = [1,2,3,4,5,6,7,'a','e' Ans:
for i in L: L = [1,2,3,4,5,6,7,'a','e']
if i==a for i in L:
break: if i=='a':
else: break
print("A") else:
print("A")
15. Rewrite the following code in python after removing all syntax error(s). Underline each correction
done in the code.
a = {'6' : "Amit", '2' : "Sunil" : '3' : "Naina"} Ans:
for i in a: a = {'6' : "Amit", '2' : "Sunil", '3' : "Naina"}
if int(i)%3=0 for i in a:
print(a(i)) if int(i)%3==0:
print(a[i])

4
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q1. What do you mean by List in Python? [1]
Q2. Write the output of the following code: [1]
>>> A = [ ]
>>> A
>>> print(A)
Q3. What do you mean by Nested list? Give example [1]
Q4. Which method is used to create an empty List? [1]
Q5. Negative indexing start from right side of the List(T/F) [1]
Q6. Write the code to convert the following string into List. [1]
“csiplearninghub”
Q7. Write a program to accept 10 numbers from the user and [2]
add even numbers in a list named “evenlist” and odd
numbers in a list named “oddlist”
Q8. Write a function evensum(list) in python that takes list of 10 [2]
numbers as argument and display the sum of all even
numbers in the list.
Q9. What is the difference between slicing and indexing of list? [2]
Q10. Write the output of the following code: [2]
L = [[1,2],[3,4],[5,6]]
print(L[0][0])
print(L[-1])
Q11. Write the output of the following code: [2]
[1,3,7,9] < [3,5,4]
[‘A’,’b’,’c’] > [‘z’]
Q12. Write the output of the following code: [4]
S = “csiplearninghub”
L = list(S)
1. print(L[-1:-5])
2. print(L[::-1])
3. print(L[1:8:2])
4. print(L[2:5])
ASSIGNMENT SET – 2
Time: 30 min M.M. – 20
Q1. What do you mean by traversing of list in Python? [1]
Ans. Traversing means to access each elements of list. This can be done with the help of the loop.
Q2. Write the output of the following code: [1]
A = [1, 2, 3, 4, 5] Ans. [3, 4, 5]
print (A[2:6])
5

Q3. Elements of list are enclosed in ________ brackets [1]


Page

Ans. Square([ ])
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Q4. Write an example of nested list. [1]
Ans. A = [1, 2, 3, [4, 5]]
Q5. Write the output of the following: (if input string is = INDIA) [1]
A = list(input(“Enter the String”))
print(A)
Ans. [‘I’,’N’,’D’,’I’,’A’]
Q6. Which method is used to remove last element of element in list? [1]
Ans. pop( )
Q7. Write a program to add only multiples of 3 from the given list. [2]
A = [12, 3, 4, 56, 7, 9, 49, 34, 6] Ans.
A = [12, 3, 4, 56, 7, 9, 49, 34, 6]
s=0
for i in A:
if i%3==0:
s=s+i
print(“Sum of all multiples of 3 is “,s)
Q8. Write a function Lavg(list) in python that takes list as argument and display the average of all [2]
numbers in the list.
Ans.
A = []
def Lavg(A):
s=0
av=0
for i in A:
s=s+i
av=s/len(A)
print(“Average is “,av)
Lavg([1,2,3,4,5,6,7,8,9,10]) #Only to verify the result
Q9. Write a function double(list) which takes list as argument and multiply each and every [2]
element of list by 2?
Ans.
A = []
def double(A):
for i in range(len(A)):
A[i]=A[i]*2
print(“List is “,A)
double([1,2,3,4,5]) #Only to verify the result
Q10. Write the output of the following code: [2]
6

A = list(“Python List Questions”) print(A[i])


Page

for i in range(len(A)-1,0,-5): Ans.


S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
s t
s n
Q11. Write the output of the following code: [2]
a=[‘a’,’b’,’c’]
b=a
a[0]=’A’
print(a)
print(b)
Ans.
[‘A’, ‘b’, ‘c’]
[‘A’, ‘b’, ‘c’]
Q12. Write the output of the following code: [4]
k = “Subscribe to my blog”
L = list(k)
1. print(L[-1:-7:-3])
2. print(L[:15:-1])
3. print(L[1:len(k):5])
4. print(L[2:-15])

7
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Practice Questions of List in Python
Q1. What do you mean by List in Python?
Ans. A list is a data structure which is mutable and ordered sequence of elements.
Q2. The elements in the list can be of ______ type (any/fixed)
Ans. any
Q3. Elements in the list are enclosed in _____ brackets
Ans. Square([ ])
Q4. Values in the list are called _______.
Ans. Item
Q5. Lists are ________ in nature (heterogeneous/homogeneous)
Ans. Heterogeneous
Q6. List is a _________ data type. (Linear/non-linear)
Ans. Linear
Q7. Elements in the list are separated by ______.
Ans. Comma (,)
Q8. Write the code to create an empty list named ‘L’.
Ans. L = [ ]
Q9. Write a code to create list of any three colors named ‘color’.
Ans. color = [“blue”, “black”, “red”]
Note : You can write any other color of your choice
Q10. What do you mean by nested list
Ans. A list inside another list is called nested list.
Q11. Write the code to create the list of::
1. Five vegetables
2. Vowels
3. First 10 natural numbers
4. Square of first 5 natural numbers.
5. Any five names of your friends
6. All the alphabets of word “Taj Mahal”
7. First five multiples of 6.
a=[“Lady Finger”, “Carrot”, “Radish”, “Cauli Flower”, “Beetroot”] (# You can write any other vegetable
also)
b = [‘a’,’e’,’o’,’i’,u’]
c = [1,2,3,4,5,6,7,8,9,10]
d = [1,4,9,16,25]
e = [‘amit’,’anuj’,’ashu’,’suman’,’mridul’] (# You can write any other names also)
f = [‘T’,’a’,’j’,’M’,’a’,’h’,’a’,’l’]
8

Q12. Write a code to convert the string “Practice” into list.


Page

Ans. a = list(“Practice”)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q13. Write the output of the following:
>>> d = “a*hj?”
>>> list(d)

Ans. [‘a’,’*’,’h’,’j’,’?’]
Q14. Write the output of the following:
>>>a = “String”
>>>list (a)

Ans. [‘S’,’t’,’r’,’i’,’n’,g’]
Q15. Write the output of the following:
>>> a = list ()
>>> a
Ans.[ ]
Q16. What is list() function?
Ans list() function is used to create empty list and it can also convert certain type of object into list.
Q17. Write the output of the following:
>>>a = input("Enter any String")
Enter any String : Practice
>>>list(a)
[‘p’,’r’,’a’,’c’,’t’,’i’,’c’,’e’]
Q18. Write the output of the following
a = [1,2,3,4,5]
print([0] Ans.
print([-1] 1
print([2] 5
print([-2] 3
print([1] 4
2
Q19. Fill the index value in place of ‘?’ as output should come as below
P
Q
L
N
T

list1 = "Practice QuesTions of List in pythoN"


list2 = list(list1)
9

print(list2[ ? ])
Page

print(list2[ ? ])

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


print(list2[ -? ])
print(list2[- ? ])
print(list2[ ? ])
Ans.
0
9
14
1
13
Q20. Write the output of the following code :
b = ['p','r','a','c','t','i','c','e']
for i in b:
print(i,end="?")
Ans.
p?r?a?c?t?i?c?e?
Q21. What do you mean by traversing a list?
Ans Traversing means to access each element of list
Q22. Write a program to print all the elements of given list using for loop.
A = [‘a’,’b’,’c’,’d’,’e’]
Ans.
A = [‘a’,’b’,’c’,’d’,’e’]
for i in A:
print(i)
Q23. List in python are mutable.(T/F)
Ans. True
Q24. Write the output of the following :
S. No Code Output (Ans.)

1 [1,2,3,4] == [4,3,2,1] False

2 [1,2,3,4] > [4] False

3 [1,2,3,4] != [1,2,3,4] False

4 [1,2,3,4] == [1,2,[3,4]] False

5 [1,2,3] == [1.0,2.0,3.0] False


10

6 >>>a = [1,2,3,4] [1,2,3,4,5,6,7,8]


>>>b = [5,6,7,8,]
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


>>>a+b

Q25. What do you mean by concatenation in list? Explain with example.


Ans 6. Concatenation of list means combining the two list. For example :
>>>a = [1,2,3,4]
>>>b = [5,6,7,8]
>>> a+b
The output will come : [1,2,3,4,5,6,7,8]
Q26. Which mathematical operator is used to concatenate the list?

Ans. ‘+’
Q27. Which mathematical operator is used to replicate the list?

Ans. ‘*’
Q28. Write the output of the following:
>>> a= “python”
>>> b=list(a)
>>> b*2
>>> b+b
>>> a+a

Ans
['p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n']
'pythonpython'
Q29. Can we multiply two list?
Ans. No
Q1. Index value of first element in list is _______________________
Ans. 0
Q2. Index value of last element in list is ____________________
Ans. -1
Q3. Write one difference between indexing and slicing.
Ans. By indexing we can extract only one element of list while by slicing we can fetch a sub list from
main list.
Q4. The syntax of slicing is:
List[start : stop : step]
Which argument is optional out of start, stop and step?
11

Ans. Step
Page

Q5. Write the output of the following:

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


b = “Practice Questions of List in Python“
a=list(b)
1. print(a)
2. print(len(a))
3. print(a[1:4])
4. print(a[1:7])
5. print(a[3:])
6. print(a[:5])
7. print(a[4:17])
8. print(a[-2:-5:-1])
9. print(a[1:7:1])
10. print(a[1:7:2])
11. print(a[-5:])
12. print(a[:4])
13. print(a[-2:-5:-2])
14. print(a[11:15])
15. print(a[:])
16. print(a[::2])
17. print(a[-5:-1])
18. print(a[7:1:-1])
19. print(a[3:-3])
20. print(a[30:40])
21. print(a[17:-1])
22. print(a[10::-1])

['P', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'Q', 'u', 'e', 's', 't', 'i', 'o', 'n', 's', ' ', 'o', 'f', ' ', 'L', 'i', 's', 't', ' ', 'i', 'n', ' ', 'P', 'y',
't', 'h', 'o', 'n']
36
['r', 'a', 'c']
['r', 'a', 'c', 't', 'i', 'c']
['c', 't', 'i', 'c', 'e', ' ', 'Q', 'u', 'e', 's', 't', 'i', 'o', 'n', 's', ' ', 'o', 'f', ' ', 'L', 'i', 's', 't', ' ', 'i', 'n', ' ', 'P', 'y', 't', 'h', 'o',
'n']
['P', 'r', 'a', 'c', 't']
['t', 'i', 'c', 'e', ' ', 'Q', 'u', 'e', 's', 't', 'i', 'o', 'n']
['o', 'h', 't']
['r', 'a', 'c', 't', 'i', 'c']
['r', 'c', 'i']
12

['y', 't', 'h', 'o', 'n']


['P', 'r', 'a', 'c']
Page

['o', 't']

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


['e', 's', 't', 'i']
['P', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'Q', 'u', 'e', 's', 't', 'i', 'o', 'n', 's', ' ', 'o', 'f', ' ', 'L', 'i', 's', 't', ' ', 'i', 'n', ' ', 'P', 'y',
't', 'h', 'o', 'n']
['P', 'a', 't', 'c', ' ', 'u', 's', 'i', 'n', ' ', 'f', 'L', 's', ' ', 'n', 'P', 't', 'o']
['y', 't', 'h', 'o']
['e', 'c', 'i', 't', 'c', 'a']
['c', 't', 'i', 'c', 'e', ' ', 'Q', 'u', 'e', 's', 't', 'i', 'o', 'n', 's', ' ', 'o', 'f', ' ', 'L', 'i', 's', 't', ' ', 'i', 'n', ' ', 'P', 'y', 't']
['P', 'y', 't', 'h', 'o', 'n']
['s', ' ', 'o', 'f', ' ', 'L', 'i', 's', 't', ' ', 'i', 'n', ' ', 'P', 'y', 't', 'h', 'o']
['u', 'Q', ' ', 'e', 'c', 'i', 't', 'c', 'a', 'r', 'P']
Q6. Write a code to make copy of following list using copy function.
a = [1,2,3,4]
Ans
>>> import copy
>>> a = [1,2,3,4]
>>> b=[Link](a)
Q7. What do you mean by append() function?
Ans. Append function add one element or a list at the end of the list.
Q8. Write the output of the following:
>>> a = [1,2,3,4]
>>> [Link](7)
>>> a
Ans. [1,2,3,4,7]
Q9. Write the output of the following
>>> a = [1,2,3,4]
>>> [Link]([7,8])
>>> a

Ans. [1,2,3,4,[7,8]]
Q1. Write a program to create list of the following (take input from the user)
a. Any five students name

b. Any five numbers

c. Any five alphabets

d. Any five name of colors.


13
Page

Ans 1 a)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


a=[]
for i in range(5):
nm=input("Enter student name")
[Link](nm)
print(a)

b)

a=[]
for i in range(5):
num=int(input("Enter any number"))
[Link](num)
print(a)

c)

a=[]
for i in range(5):
al=input("Enter any alphabet")
[Link](al)
print(a)

d)
a=[]
for i in range(5):
cl=input("Enter name of any color")
[Link](cl)
print(a)
Q2. Write a program to accept 10 numbers from the user, if the number is odd, and then add that
number to the list.
(input numbers are : 1,2,3,4,5,6,7,8,9,10
L = [1, 3, 5, 7, 9])

a = []
for i in range(10):
num=int(input("Enter any number"))
if(num%2!=0):
14

[Link](num)
print(a)
Page

Q3. Write a program to find the largest number from the following list.(without using inbuilt function)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


A = [23, 12, 45, 67, 55]

Ans.
A = [23, 12, 45, 67, 55]
max=A[0]
for i in range(len(A)):
if A[i]>max:
max=A[i]
print(max)
Q4. Write a program to find the second largest number from the following list.

A = [23, 12, 45, 67, 55]

Ans
A = [23, 12, 45, 67, 55]
[Link]( )
print(A[-2])
Q5. Explain the extend() function with example.

Ans. extend() function add complete list or specified elements of list at the end of another list. for
example
A = [23, 12, 45, 67, 55]
B = [“Amit”,2,3]
[Link](B)
print(A)
OUTPUT : [23, 12, 45, 67, 55, ‘Amit’, 2, 3]
Q6. Write any one difference between insert() and append() function.

Ans. insert() function add elements at the specified index of list while append() function add the
elements at the end of the list.
15
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Practice Questions of List in Python
Practice Questions of List in Python – Test 6
Q1. Write the role of reverse() function in list.

Ans reverse() function arrange the elements of list in the reverse order.
Q2. reverse() function create new list. (T/F)

Ans. False
Q3. >>> a = [1,2,3,4]
>>> [Link]()
>>> print(a)
Write the output of above code.

Ans. [4,3,2,1]
Q4. What type of error return by index() function, if element is not present in list?

Ans. Index error


Q5. a = [1,5,7,5]
b = [Link](5)
print(b)
Write the output of above code.

Ans. 1
Q6. Write the output of the following code :
a = [1,2,3,4]
a[1] = 'a'
print(a)

Ans. [1,a,3,4]
Q7. len() function returns the ______ of the list.
16

Ans length
Page

Q8. By default sort() function arrange the elements in ________ order (increasing/decreasing)
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Ans. increasing
Q9. Write code to arrange elements of following list in increasing order.
A = [23,12,45,32,67,33]

Ans. [Link]()
Q10. What do you mean by nested list. Give one example of nested list.

Ans. A list inside another list is called nested list. for example
A = [1,2,3,[‘a’,’b’]]
Practice Questions of List in Python – Test 7
Q1. Explain the following functions in reference to list with example
a. count()
b. clear()
c. pop()
d. remove()
Q2. What is the difference between del statement and pop() function.
Q3. Write the output of the following:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [Link](5)
c = [Link]( )
d = [Link](-1)
print(b)
print(c)
print(d)
print(a)
Q4. Out of del and pop() which one return the deleted element.
Q5. remove() function take _______ (element/index) as argument.
Q6. Name a function/statement which can delete more than one element from the list.
Q7. Name a function which can delete only one element from the list.
Q8. Write a program to delete/remove all the negative elements from the list.
Q9. Write a program to delete/remove all the odd numbers from the list.
Q10. Write a program to delete/remove all the numbers less than 10 from the list. 17

Practice Questions of List in Python


Practice Questions of List in Python – Test 8
Page

Q1. Write a program to check whether a number (accepted from user) is present in a list.

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q2. Name a function which is used to find the largest number from a list.
Q3. ______ function returns the smallest value from the list.
Q4. max() function works in a list which have all values of same data type. (T/F)
Q5. Write the full form of ASCII value.
Q6. ASCII value of ‘A’ is ______.
Q7. ASCII value of ‘b’ is ______.
Q8. Write the output of the following:
a = [11,42,31,14]
print(max(a))
print(min(a))
print([Link](42))
Q9. Write the output of the following:
a = [11,42,31,’a’,14]
print(max(a))
Q10. Write the output of the following:
a = [‘amit’,’Amit’,’Amita’]
print(max(a))
print(min(a))

Practice Questions of List in Python


Practice Questions of List in Python – Test 9
Q1. Write a program to input a number and count the occurrence of that number in the given list.
B = [34,21,3,12,34,56,76,5,4,21,12,34]
Q2. Write a program to separate the character and numeric value from a given list and store them in a
separate list.
A = [1,’f’,2,’b’,3,4,’h’,j’,6,9,0,’k’]
Q3. What do you mean by sorting?
Q4. Name any two sorting techniques.
Q5. Write a program to create a list of 10 integers and sort the list in increasing order using bubble sort.
Q6. Suppose total element in a list are 7, so how many times the outer loop will be executed in bubble
sort.
Q7. A = [23,45,21,78,43]
Write the order of the elements in the above list after first pass of bubble sort (in ascending order).
Q8. Write any one application of bubble sort.
18
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


19
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Class 12 Computer Science Data Structure in Python Handout
Table of Contents
1. Data structure in Python
2. What is Stack
1. Operations on Stack
2. Working with stack using list.
3. Practice Questions – Part 1
4. Practical Implementation of stack using list
3. What is Queue?
1. Operations on Queue
2. Queues in daily life
3. Working with queue using list
4. Practice Questions – Part 2
5. Practical Implementation of queue using list
Data Structure
A data structure in python can be defined as a structure which can holds related data. In other words
we can say that data structure is a way of storing, organizing and fetching data in computer. There are
four data structure in python :
1. List
2. Tuple
3. Dictionary
4. Set
In this handout we will learn that how List can be implemented as STACK & QUEUES
STACK :
A stack is a linear data structure in python in which addition and deletion of elements can be done at
one end only. A stack is known as LIFO (Last – In, First – Out) data structure in python. LIFO means the
elements which are added in the last would be the first one to remove. Examples of stack are pile of
books, pile of plates or stack of carom coins.

20
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Class 12 Computer Science Data Structure in Python Handout
In above pile of rings the ring which we placed first is at the bottom and the ring which we placed in last
is at the Top, So we can say that Stack is linear list implemented as LIFO.
Operations on Stack:
There are two main operations on Stack:
Addition of element on the Top of the Stack is called PUSH.

1. push (4)
2. push (7)
3. push ("a")
4. push ("Suman")

Above operations will form the stack as shown below :

Class 12 Computer Science Data Structure in Python Handout


So you can observe that the element which we inserted first is coming at the bottom of the stack.
In the form of List the above stack can be shown as.
21
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Class 12 Computer Science Data
Structure in Python Handout
Removal of elements from the top of the Stack is called POP.

In the form of List the above stack will be represented as shown below

Class 12 Computer Science Data Structure in


Python Handout
Working with Stack using List:
The implementation of stack using list is a simple process as there are inbuilt function which we used
during working with stack. Basic operations that we should know are :
1. How to create an empty stack?
2. How to add elements to a stack?
3. How to delete / remove elements from the stack
4. How to traverse or displaying elements of stack?
5. How to check for empty stack?
1. Creating an Empty Stack : An empty stack can be created by using the following code
st = [ ] or st = list( ) #Here st is an empty stack
NOTE : Working with stack is similar to working with list (we can add element by append( ), we can
remove element by pop( ) and we can display element by using index value)
22

2. Adding an element to a Stack : We can add element in a stack by using append( ) function as shown
below
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


[Link](5)
Here element ‘5’ is added into a stack named ‘st’
NOTE : We can add element only at the end of the list as we are implementing list as stack.
3. Deleting elements from the stack : We can delete elements from the stack as shown below :
[Link]( )
NOTE : We can remove or delete element only from the end of the list as we are implementing list as
stack.
4. Displaying all elements of the stack : We can display all elements in stack as shown below :
L = len(st)
for i in range(L-1, -1, -1) : #As we have to display elements in reverse order
print(st[i])
if (st == [ ]) :
print("stack is empty")
Data Structure in Python – Question Answer Session – Part 1
Q1. Expand the term LIFO.
Q2. What do you mean by Stack?
Q3. What is the difference between pop( ) and append( ) function of list?
Q4. What do you mean by data structure?
Q5. Write a code to create an empty stack named "st".
Q6. Write the technical term used for adding element in stack.
Q7. What happen when you try to delete an element from an empty stack?

Practical Implementation of Stack using List


Q1. Write a function push(student) and pop(student) to add a new student name and remove a student
name from a list student, considering them to act as PUSH and POP operations of stack Data Structure
in Python.
st=[ ]
def push(st):
sn=input("Enter name of student")
[Link](sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",[Link]())
Q2. Write a function push(number) and pop(number) to add a number (Accepted from the user) and
remove a number from a list of numbers, considering them act as PUSH and POP operations of Data
23

Structure in Python.
Page

st=[ ]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


def push(st):
sn=input("Enter any Number")
[Link](sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted Number is :",[Link]())
Q3. Write a menu based program to add, delete and display the record of hostel using list as stack data
structure in python. Record of hostel contains the fields : Hostel number, Total Students and Total
Rooms
host=[ ]
ch='y'
def push(host):
hn=int(input("Enter hostel number"))
ts=int(input("Enter Total students"))
tr=int(input("Enter total rooms"))
temp=[hn,ts,tr]
[Link](temp)

def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",[Link]())

def display(host):
l=len(host)
print("Hostel Number\tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])

while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
24

op=int(input("Enter the Choice"))


if(op==1):
Page

push(host)
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
For more questions on Data Structure in Python Click Here
Queue :
A queue is a specialized data structure in which elements are added at one end called Rear and
removed from other end called Front.
Operations on Queue :
A queue performs only two operations :
1. Insert : In this a new element is added at the end of list called Rear.
2. Delete : In this an element is to be deleted from one end called Front.
NOTE : Insertion and Deletion of elements takes place at different end. Addition at Rear and Deletion at
Front
Queues in Daily Life :
We can see the formation of queues in our daily life like :
1. Outside the ATM
2. In Bank
3. Buying Ticket in Movie Hall
Working with Queue using List:
The implementation of queue using list is a simple process as there are inbuilt function which we used
during working with queue. Basic operations that we should know are :
NOTE : Enqueue term means adding element in queue while Dequeue term means deleting element
from queue
1. How to create an empty queue?
2. How to add elements to a queue?
3. How to delete / remove elements from the queue
4. How to traverse or displaying elements of queue?
5. How to check for empty queue?
1. Creating an empty queue : We can create an empty queue as similar to stack like :
Q = list( ) or Q = [ ]
2. Adding an element to queue : Elements can be added by using the function append( ) of list. This
function automatically add the new element at the end of the queue. like –
[Link](4) : This code will add element 4 at the end of the queue named “Q”
25

3. Deleting an element from Queue : pop( ) function is used to delete an element from the queue.
Before deleting an element, it is to be checked that whether queue is empty or not. Code to delete an
Page

element is :
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
if (Q == [ ]:
print("Queue is Empty")
else :
print("Deleted element is :", [Link](0)) # index value "0" indicate the very first value of the queue
4. Displaying elements of the queue : Elements of the queue can be displayed as given below :
L = len(Q)
for i in range(0, L):
print(Q[i])
5. Checking an empty Queue : We use the following code to check whether the queue named “Q” is
empty or not.
if(Q==[ ]):
print("Queue is Empty")
Data Structure in Python – Question Answer Session – Part 2
Q1. What is the difference between Stack and Queue data structure in python?
Q2. In queue, addition and deletion of elements take place at different ends(T/F)
Q3. Which method of list is used to add element at the end ?
Q4. Write the code to display all elements of queue named "Aqueue".
Q5. Write a function addQ(num) to add numbers in a queue using list. (num is a list of numbers)
Q6. Write full form of FIFO.
Q7. Queue works on _______________(FIFO/LIFO) concept.
Q8. Write 2 applications of stack.
Q9. Which method of list is used to remove last element of the list?
Practical Implementation of queue using list
Q1. Write a function Aqueue(student) and Dqueue(student) to add a new student name and remove a
student name from a list student, considering them to act as insert and delete operations of the queue
Data Structure in Python.
student=[ ]
def Aqueue(student):
sn=input("Enter name of student")
[Link](sn)

def Dqueue(student):
if(student==[]):
print("Queue is empty")
else:
print("Deleted student name :",[Link](0))
Q2. Write a function Add(book) and Del(book) to add a new book name and remove a book name from
26

a list book, considering them to act as insert and delete operations of the queue Data Structure in
Python.
Page

book=[ ]
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
def Add(book):
bn=input("Enter name of book")
[Link](bn)

def Del(book):
if(book==[ ]):
print("Queue is empty")
else:
print("Deleted book name :",[Link](0))
Q3. Write a menu driven program using function Qadd( ), Qdel( ) and disp( ) to add, delete and display
the record of book using queue as data structure in python. Record of book store the following details :
Book name, Book Number and Book Price
book=[ ]
ch='y'
def Qadd(book):
bn=input("Enter book name")
bnum=int(input("Enter book number"))
bp=int(input("Enter book price"))
temp=[bn,bnum,bp]
[Link](temp)

def Qdel(book):
if(book==[ ]):
print("No Record")
else:
print("Deleted Record is :",[Link](0))

def disp(book):
l=len(book)
print("Book Name\tBook Number\tBook Price")
for i in range(0,l):
print(book[i][0],"\t\t",book[i][1],"\t\t",book[i][2])

while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
27

print("4. Exit")
op=int(input("Enter the Choice"))
Page

if(op==1):
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Qadd(book)
elif(op==2):
Qdel(book)
elif(op==3):
disp(book)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")

28
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Python Fundamentals Practice Questions – Test 1
Q. Name two modes of Python.

Ans. Interactive Mode and Script Mode


Q2. Write Full Form of IDLE

Ans. Integrated Development Learning Environment


Q3. Interface mode of python is also known as _______________.

Ans. Python Shell


Q4. In which mode we get result immediately after executing the command?

Ans. Interactive mode


Q5. Write the output of the following.
a. >>> x = 5

>>> y = 7

>>> print(x + y )

b. >>> print(2 **5)

Ans
a. 12
b. 32
Q6. Write one drawback of interactive mode.

Ans. We can not save our commands


Q7. Ananya purchased 5 pencils and 2 erasers at the cost of Rs 7 and Rs 5 respectively. Write the
program to calculate & display the total amount paid by ananya.

Ans.
penc = 7

er = 5

totcost = penc * 5 + 2 * er
29

print("Total cost paid by Ananya is",totcost)


Page

Q8. What do you mean by comments in Python?

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans. Non executable lines are called Comments
Q9. Which symbols are used for single line comments and multiple line comments?

Ans. # symbol
Q10. What do you mean by variable?

Ans. Named storage location of value is called variable


Python Fundamentals Practice Questions – Test 2

Q1. What is the purpose of creating variables?

Ans. Variables are used to store values which we can use later in our programs.

Q2. Write code to find the address of variable.

Ans. id command is used to find the address of variable for example, to find the address of variable ‘x’
code is
>>>id(x)

Q3. What do you mean by data type?

Ans. Data type refers to the type of value used for example integer, float string etc

Q4. Write three numeric data type in python.

Ans. Integer, Floating Point and Complex

Q5. Name three sequential data types in python.

Ans. List, tuple and String


Q6. >>> x = 200
>>> y = 10.5
Write the data type of variable x and y.
30
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans. a. Integer
b. Floating point

Q7. Data type of variable is according to the value it holds.(T/F)

Ans. True

Q8. Which data type store the combination of real and imaginary numbers?

Ans. Complex

Q9. Write the output of the following:


>>> 4.7e7
>>> 3.9e2

Ans.
47000000
390

Q10. Which data type return value True or False?

Ans. Boolean
Python Fundamentals Practice Questions – Test 3
Q1. Write the output of the following :
1. >>> (75 > 2 **5)
2. >>> (25 != 5 *2)

1. True
2. True
Q2. Which operator can be changed in above part (2) so that it returns True?

Ans. == in place of !=
Q3. Dictionary is enclosed in ___________ brackets.

Ans. Curly braces {}


31

Q4. What do you mean by keywords in python?


Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans. Keywords are reserved words. We can not use keywords for variable name or any other identifier.
Q5. Keywords can be used as variable names (T/F)

Ans. False
Q6. Write the code to display all keywords in python.

Ans import keyword print([Link])


Q7. Write two keywords which start with capital letters.

Ans. True, False


Q8. Write the output of the following
>>> str = "Informatics"
>>>str[3] = 'e'
>>> print(str)

Ans. Type Error


Q9. Write the output of the following:
>>> a = [1,2,3]
>>>a[0] = 6
>>>print(a)

Ans. [6, 2, 3]
Q10. Name three types of operators in python.

Ans. 1. Mathematical Operator 2. Comparison Operator 3. Logical Operator


Python Fundamentals Practice Questions – Test 4
Q 1. What do you mean by Escape sequence?

Ans The sequence of characters after backslash is called escape sequence.

Q 2. Write the output of the following


>>> x = 2 + 5j
>>> print([Link], [Link])

Ans. 2.0 5.0


32
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q 3. What is None data type?

Ans. This data type is used to define null value or no value.


for example
m = none, Now the variable 'm' is not pointing to any value, instead it is pointing to none.

Q 4. Write the output of the following

>>> v1 = 10

>>> v2 = None

>>> v1

>>> v2

>>>print(v2)

Ans.
10
None

Q 5. What is the purpose of type() function?

Ans. This function tell us about the data type of a variable. for example
a = 10
print(type(a))
OUTPUT : <class 'int'>

Q 6. Write the output of the following.


33

>>> type(10)
Page

>>>type('10')

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


>>>type(10.0)

>>>type(True)

>>>type('False')

Ans. <class 'int'>

<class 'str'>

<class 'float'>

<class 'bool'>

<class 'str'>

Q 7. Which function is used to find the data type of variable?


Ans. type() function
Q 8. Write the output of the following
>>> a = "hello"
>>> b = 10
>>> c = 9.8
>>> d = 7 + 3.6j
>>> print(a)
>>> print(b)
>>> print(c)
>>> print(d)
Ans
hello
10
9.8
7 + 3.6j

Q9. Identify the variable name, variable type, value and operator used in the following statement.
34

>>> x = 9
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans.
variable name -- x
variable type -- integer
value -- 9
operator -- =

Q 10. What do you mean by assignment operator?


Ans. An operator which is used to assign a value to a variable is called assignment operator. Symbol of
assignment operator is '=', for example
c = 10, value 10 will be assigned to variable 'c'
Python Fundamentals Practice Questions Test 5
Q1. Write the output of the following :
>>> x = 8
>>> x = 5
>>> print (x + x)
Ans. 10

Q2. Is the following statement correct?


>>> a, b, c = 2 , 3 , 'Amit'
Ans. yes

Q3. Identify the invalid variable names from the following and specify the reason also.
a) m_n
b) unit_day
c) 24Apple
d) #sum
e) for
f) s name
Ans. 24apple : Variable can not start with number
#sum : Variables can not start from special character.
for : Keyword can not be used as variable
s name : Spaces are not allowed in variable names

Q4. What are keywords?


Ans. Keywords are reserved words which have special meanings to python
35

Q5. Keywords can be used as variable names (T/F)


Ans. False
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q6. Write the code to display all the keywords available in python.
Ans.
import keyword
print([Link])

Q7. What do you mean by expression?


Ans. A combination of operators and operands is called expression.
like - a + b * c

Q8. Write the python expressions equivalent to the following algebraic/arithmetic expressions
z = u/5
z = 9ab + d
z = x+4/j + 7
Ans.
1. z = u/5
2. z = 9*a*b + d
3. z = x + 4/j + 7

Q9. What are operators? Name three types of operators.


Ans. Operators are special symbols that perform a specific task (arithmetic
or logical operations)
Three types of operators are
1. Logical Operators
2. Relational Operator
3. Mathematical Operator

Q10. >>> 7 % 10 will return ____________________


Ans 7
Python Fundamentals practice Questions Test 6
Q1. Write the output of the following:

print("hello * 5")
print("hello" * 5)
print("***" * 5)
print("Hello", "how", "R", "U")
print("Hello" + "how" + "R" + "U")
print("Amit" + "Sethi")
36

print(23 + 9)
print ("7 + 9")
Page

print(7/6)
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
print(7//6)
print(8 % 2)
print(3 % 7)
print(4 ** 3)
print (7 * 5)
print (8 - 16 )

Ans
hello * 5
hellohellohellohellohello
Hello how R U
HellohowRU
AmitSethi
32
7+9
1.1666666666666667
1
0
3
64
35
-8

Q2. What do you mean by string concatenation? Give example

Ans. String Concatenation means joining the strings. for example


>>>s = "Amit" + "Sethi"
>>> print(s)
Output is :
AmitSethi

Q3. What do you mean by binary and unary operators? Give one example of each.

Ans. Binary operators work on two or more operands like Division (+), Multiplication (*).
2/3
4*3
Unary operators work only on one operand like Subtraction (-)
37

-9
-7
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q4. Evaluate the following expressions
23 + 4 **2
9*3-8+6
7%2 + 7//2
67 + 3%3
12 % 4 + 6 + 4 // 3
Ans
39
25
4
67
7

Q5. Write the name and purpose of the following operators.


//
%
**
*

Python Fundamentals Practice Questions Test 7


Q1. Out of relational and arithmetic operators which have higher precedence?
Ans. Arithmetic Operators

Q2. Write the output of the following


>>>35 < 6
>>>5 > 2**2
>>>7 != 3.5 *2
>>>7 == 3.5 ** 2
>>> "Anil" > "Anita"
Ans.

False
True
False
True
False
38

Q3. What do you mean by shorthand operator?


Ans.
Page

A combination of assignment and binary operator is called shorthand operator. for example
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
x=x+2 can be written with shorthand operator as x +=2

Q4. Write the output of the following if x = 8.


>>> x + = 8
>>> x - = 8
>>> x * = 8
>>> x ** = 2
>>> x % = 8
>>>x / = 8
>>> x // = 8
Ans.
16
0
64
64
0
1.0
1

Q5. What is the purpose of input function?


Ans. input() function is used to take/accept data from the user.

Q6. Write a program to accept name from the user and display "Hello <name>"

Q7. Write a program to accept the first name and last name from user and display the full name.
Ans.
fname=input("Enter your first name")
lname=input("Enter your last name")
print("Complete name is",fname , lname)

Q8. Write a program to accept two numbers from the user and display their sum and product.
Ans.
n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
print("Sum is ",n1+n2)
print("Product is ", n1*n2)
39

Python Fundamentals Practice Questions Test 8


Q1. What is the difference between eval() and int() function?
Page

Ans. eval( )
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
function return error on passing integer argument while int( ) function does not return error.
for example :
print(eval(12)) returns error
print(int(12)) returns 12

Q2. What do you mean by function?


Ans.
A set of statement in a program which perform a specific function is called function.

[Link] the output of the following


>>>eval('15')
>>>eval("6")
>>>eval(7)
>>>eval("5 + 8 * 6)
Ans.
15
6
Error
53

Q4. def command is used to define a function or to call a function.


Ans. def is used to define a function

Q5. Write a user defined function to find the area of rectangle.


Ans.
def area_rect( ):
len=int(input("Enter length of rectangle))
br=int(input("Enter breadth of rectangle))
area=len*br
print("Area of rectangle is " , area)

Q6. Write a user defined function to print "Python Fundamentals" five times.

Q7. Write a user defined function to find the volume of cube.


Ans.
def area_cube( ):
side = int(input("Enter side of cube"))
40

print("Volume of cube is " , side*side*side)


Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q8. All statements in python are terminated by semicolon.(T/F)
Ans. False

Q9. How many spaces are there in one indentation level?


Ans. 4

Q10. In python one line can be of maximum ___________ characters.


Ans. 79
Python Fundamentals Practice Questions Test 9
Q1. What do you mean by comment in python?
Ans. Non executable lines in python are called comment. Comment in python begin with symbol '#'

Q2. A comment in python starts with __________ symbol.


Ans. #

Q3. Is python a case sensitive?


Ans. Yes

Q4. What do you mean by dynamic typing?


Ans. When we do not declare the type of variable before assigning a value is called dynamic typing.

Q5. Define the following term


Token
Keyword
String
Operators
int() function
type() function

Ans.
Smallest unit/element of python program is called token.
Those words which have special meaning for the interpreter of python are called keywords.
Sequence of characters which are enclosed in single or double quotes is called string
An Operator is a symbol or a word that perform a specific operation(Mathematical,
Logical, Comparison) on operands and return the result.

int() : This function converts the String to integer. for example


41

print(int("123")) will print 123 as integer.


Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q6. Precision of _________ digits in floating point numbers in python.
Ans. 15

Q7. input() function always return a value of __________ type.


Ans. String

Q8. Write the output of the following


>>> x , y = 3, 5
>>>x, y = y, x + 6
>>> print(x,y)
Ans. 5 9

Q9. What is the extension of python file?


Ans. .py

Q10. Find the error in the following code


def sub(n1, n2)
res = n1 - n2
return res
Ans. Correct code is

def sub(n1,n2):
res = n1 - n2
return res
Python Fundamentals Practice Questions Test 10
Q1. Write a program to accept radius of circle and display it's area and circumference.
Ans.
import math
r=int(input("Enter radius of circle"))
print("Area of Circle is ",[Link]*r*r)
print("Circumference of Circle is ",2*[Link]*r)

Q2. Write a program to find the average marks of five subjects. (Accept marks from user)
Ans
m1=int(input("Enter marks of Subject-1 :"))
m2=int(input("Enter marks of Subject-2 :"))
m3=int(input("Enter marks of Subject-3 :"))
42

m4=int(input("Enter marks of Subject-4 :"))


m5=int(input("Enter marks of Subject-5 :"))
Page

s = m1+m2+m3+m4+m5
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
print("Average marks of five subjects ",s/5)

Q3. Write a program to find the area of right angle triangle. (Accept base and height from user)
Ans.
b=int(input("Enter the base of triangle :"))
h=int(input("Enter the height of triangle :"))
print("Area of triangle is :",1/2*b*h)

Q4. Write a program to print the following pattern without loop.


*
**
***
****

Ans.
for i in range(1,5):
for j in range(i):
print("*",end=" ")
print()

Q5. Write a program to find the volume of sphere.(Accept radius from the user)
Ans.
import math
r=int(input("Enter the radius of sphere"))
print("Volume of sphere is ",4/3*[Link]*r*r*r)

Q6. Find errors


a = input(Enter your name)
b = input("Enter any number")
Ans. Correct statements are
a=input("Enter your name")
b=int(input("Enter any number"))

Q7. Find errors:


a = input("Enter your name"
Print(Your name is, a)
43

Ans. Correct code is :


a = input("Enter your name")
Page

print("Your name is: ", a)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q8. Write the output of the following
a, b = 2, 6
a, b, b = a+b, 2, 3
print(a,b)
Ans.
83

Q9. Write the output of the following.


a=5
b = "Amit"
print(a + b)
Ans. It will show ERROR

Q10. Write the output of the following.


a =3
b =4
print(a + b%2 + a**2)

Ans.12

44
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Python Output based Questions-Test 1
Q1. Write the output of the following code:
[1]:
for i in range(5):
print(i)

0
1
2
3
4

[2]:
for i in (1,2,3):
print(i)

1
2
3

[3]:
for i in (2,3,4):
print("i")

i
i
i

[4]:
for i in (4,3,2,1,0):
print(i, end=" ")

43210
[5]:
for i in range(10):
if(i%2!=0):
print("Hello",i)
45

Hello 1
Page

Hello 3

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Hello 5
Hello 7
Hello 9

[6]:
for i in range(10,2,-2):
print(i, "Hello")

10 Hello
8 Hello
6 Hello
4 Hello

[7]:
str = "Python Output based Questions"
word=[Link]()
for i in word:
print(i)

Python
Output
based
Questions

[8]:
for i in range(7,10):
print("Python Output based Questions")
print("Python Output based Questions")

Python Output based Questions


Python Output based Questions
Python Output based Questions
Python Output based Questions

[9]:
for i in range(7,-2,-9):
for j in range(i):
print(j)
46

0
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


1
2
3
4
5
6

[10]:
i="9"
for k in i:
print(k)

Python Output based Questions-Test 2


Q2. Write the output of the following code :
[11]:
for i in range(1,8):
print(i)
i+=2

1
2
3
4
5
6
7

In [12]:
for i in range(4,7):
i=i+3
print("Hello")

Hello
Hello
Hello
47

[13]:
Page

for i in range(4,7):

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


i=i+3
print("Hello",i)

Hello 7
Hello 8
Hello 9

[14]:
i=4
while(i<10):
i=i+3
print(i)

7
10

[15]:
for i in range(20):
if i//4==0:
print(i)

0
1
2
3

[16]:
x=1234
while x%10:
x=x//10
print(x)

123
12
1
0

[17]:
48

for i in 1,2,3:
print(i*i)
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


1
4
9

[18]:
for i in 2,4,6:
print("H"*i)

HH
HHHH
HHHHHH

[19]:
p=10
q=20
p=p*q//4
q=p+q**3
print(p,q)

50 8050

[20]:
x=2
y=6
x=x+y/2 + y//4
print(x)

6.0
Python Output based Questions-Test 3
Q3. Write the output of the following.
[21]:
n=11
for i in range(2,n//2):
if n%i!=0:
print("Python Output based Questions")
break
else:
print("Bye")
49

[22]:
Page

n=20

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


for i in range(2,n//4):
if n%i==0:
print("Python Output based Questions")
else:
print("Bye")

Python Output based Questions


Bye
Python Output based Questions

[23]:
for i in 123:
print(i)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-f5b16f0d3ced> in <module>
----> 1 for i in 123:
2 print(i)

TypeError: 'int' object is not iterable


[24]:
for i in [10,20,30]:
print("Hello",i)

Hello 10
Hello 20
Hello 30

[25]:
x=2
for i in range(x**2,x,-1):
print(x)

2
2

[26]:
50

x=10
for i in range(x):
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


if x==5:
break
print("H")
print(x)

10

[27]:
x=6
for i in range(x):
if x==5:
break
print("H")
print(x)

H
H
H
H
H
H
6

[28]:
s=0
for i in range(5):
s=s+i
print(s)

0
1
3
6
10

[29]:
for i in range(1,11):
print("%d"%i)
51

1
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


2
3
4
5
6
7
8
9
10

[30]:
print((3>1) and (9<1))

False

Python Output based Questions-Test 4


Q4. Write the output of the following code:
[31]:
print((9>1) or (9<1))

True

[32]:
f=0
while(f<10):
print(f)
f=f*3

Loop will run infinite


[33]:
for i in range(5):
for j in range(i):
i=i+j
print(i,end="@")
print(j)

1@2@3@3@4@6@4@5@7@10@3
52

[34]:
i=0
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


while(i<5):
for j in range(i):
print(j,end="s")
i=i+1

0s0s1s0s1s2s0s1s2s3s
[35]:
num1=7
num2=10
for i in range(5):
num2=num2+10
print(num2)
print(num1)

20
7
30
7
40
7
50
7
60
7

[36]:
s=0
for i in range(-5,5):
s=s+i
print(s)

-5

[37]:
for i in range(5):
if i%2==0:
pass
else:
53

print(i)
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


1
3

[38]:
for i in range(5):
if i%2==0:
continue
else:
print(i)

1
3

[39]:
for i in range(1,5):
if i%2==0:
break
else:
print(i)

[40]:
for i in range(5):
while(i):
print(i,end=" ")
i=i-1
print()

1
21
321
4321

Python Output based Questions-Test 5


Q5. Write the output of the following code :
[41]:
x=5
54
Page

while(x<15):

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


print(x**2)
x+=3

25
64
121
196

[42]:
a=7
b=5

while(a<9):
print(a+b)
a+=1

12
13

[43]:
b=5

while(b<9):
print("H")
b+=1

H
H
H
H

[44]:
b=15

while(b>9):
print("Hello")
b=b-2
55

Hello
Hello
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Hello

[45]:
x=15

while(x==15):
print("Hello")
x=x-3

Hello

[46]:
x = "123"

for i in x:
print("a")

a
a
a

[47]:
i=9

while True:
if i%3==0:
break
print("A")

Loop will not execute


[48]:
a=5

while(a<=10):
print("a")
a+=1
56

a
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


a
a
a
a

[49]:
i=0

while i<3:
print(i)
i=i+1
else:
print(7)

0
1
2
7

[50]:
i=0

while i<3:
print(i)
i=i+1
print(0)

0
0
1
0
2
0

Python Output based Questions-Test 6


Q6. Write the output of the following code :
[51]:
i=2
57
Page

for x in range(i):

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


i+=1
print(i)
print(i)

3
3
4
4

[52]:
i=2

for x in range(i):
x+=1
print(x)
print(x)

1
2
2

[53]:
i=2

for x in range(i):
x+=1
print(x)
print("x")

1
x
2
x

[54]:
i=100

while i<57:
58

print(i)
Page

i+=5

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Loop will run infinite times
[55]
for i in range(5):

for j in range(i):

print("A",end=" ")

print()

A
AA
AAA
AAAA

[56]
for i in range(5):

for j in range(i):

print("A",end="a")

print()

Aa
AaAa
AaAaAa
AaAaAaAa

[57]
for i in range(5):

print("AS"*i,"\n")[/showhide]
59

AS
Page

ASAS

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


ASASAS
ASASASAS

[58]
for i in range(5):

for j in (i):

print("AS"*i,"\n")

[59]
print(10*2//3**2)

[60]
print(12+34-320+23**2)

64

Python Output based Questions-Test 7


Q7. Write the output of the following code :
[61]
a=7
for i in 7:
print(a)

Ans. Shows Error


[62]
a = "AMIT"
for i in range(len(a)):
print(a)

Ans.
AMIT
AMIT
AMIT
60

AMIT
Page

[63]

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


x = "Welcome to my blog"
j = "i"
while j in x:
print(j)

Ans. Loop will execute infinite times.


[64]
print(range (5, 0, -2))

Ans. range (5, 0, -2)


[65]
for i in range(0,2,-1):
print("Hello")

Ans. No Output
[66]
s1="[Link]"
s2=""
s3=""
for x in s1:
if(x=="s" or x=="n" or x=="p"):
s2+=x
print(s2,end=" ")
print(s3)

Ans. spnn
[67]
s1="[Link]"
c=0
for x in s1:
if(x!="l"):
c=c+1
print(c)

Ans. 18
[68]
j=12
c=9
61

while(j):
if(j>5):
Page

c=c+j-2

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


j=j-1
else:
break
print(j, c)
print(c)

Ans.
5 58
58
[69]
L = [13 , 12 , 21 , 16 , 35 , 7, 4]
s=5
s1 = 3
for i in L:
if (i % 4 == 0):
s=s+i
continue
if (i % 7 == 0):
s1 = s1 + i
print(s , end=" ")
print(s1)

Ans. 37 66
[70]
print('cs' + 'ip' if '234'.isdigit() else 'IT' + '-402')

Ans. csip

62
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Table of Content
1. Practice Questions of String in Python – Test 1
2. Practice Questions of String in Python – Test 2
3. Practice Questions of String in Python – Test 3
4. Practice Questions of String in Python – Test 4
5. Practice Questions of String in Python – Test 5
6. Practice Questions of String in Python – Test 6
7. Practice Questions of String in Python – Test 7
8. Practice Questions of String in Python – Test 8
9. Practice Questions of String in Python – Test 9
10. Practice Questions of String in Python – Test 10
Practice Questions of String in Python – Test 1
Q1. What is String in Python?

Ans. A sequence of character which are enclosed in single(‘ ‘) or double (“”) quotes is known as String.
Q2. Is there any difference in ‘a’ or “a” in python?

Ans. No
Q3. Is there any difference between 1 or ‘1’ in python?

Ans. Yes
Q4. Python treats single quotes same as double quotes.(T/F)

Ans. True
Q5. A string with zero character is called __________ string.

Ans. Empty
Q6. Python does not support a character type.(T/F)

Ans. True
Q7. Write a code to store following String in a variable named ‘str’. This is Amit’s Blog

Ans. str=”This is Amit\’s Blog”


Q8. Write the output of the following code:
str1 = "Welcome to my blog"
str2 = "Welcome to my \n Blog"
print(str1)
print(str2)
63
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans.
Welcome to my blog
Welcome to my
Blog
Q9. Write the output of the following.
str1 = "Welcome \tto my Blog"
str2 = "Welcome to\n my \tBlog
print(str1)
print(str2)

Ans.
Welcome to my Blog
Welcome to
my Blog

Q10. Write the output of the following.


str1 = “”” Welcome to my
blog.
This is for
Class X”””
print(str1)

Ans.
Welcome to my
blog.
This is for
Class X
String in Python
Practice Questions of String in Python – Test 2
Q1. Write the output of following code-

a) str="hello"
print(str[:3])

Ans : hel
b) str=’My Blog’
a=’ ‘
64

for i in range(len(str)):
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


a+=str[i]
print(a)

Ans: My Blog
c) str='MyBLog'
a=' '
for i in range(len(str)):
print(a*str[i])

Ans:
y
BB
LLL
oooo
ggggg
d)
s='My'
s1='Blog'
s2=s[:1]+s1[len(s1)-1:]
print(s2)

Ans. Mg

e) print(“My”+’Blog’ * 2)

Ans. MyBlogBlog

f) print(“My” *3 + “Blog” +’7′)

Ans. MyMyMyBlog7
g) for i in range(2,7,2):
print(i * '2')

Ans.222222222222
h) for i in range(3,12, 2):
print("a".upper())

Ans.
A
65

A
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


A
A
i) for i in range(3,12,13):
print("a".upper)

Ans. <built-in method upper of str object at (some memory address)>


j) s='Welcome to My Site [Link] '
print([Link]('come'))
print([Link]('o'))
print([Link]('o', 10, 20))
print([Link]('o', 5, 10))

Ans.
3
4
-1
9
Practice Questions of String in Python – Test 3
String in Python
Q1. Write a code to create empty string 'str1'

Ans. str1 = ' '

Q2. What do you mean by traversing a string?

Ans. Traversing a string means accessing all the elements of the string one by one by using index value.

Q3. What is the index value of first element of a string?

Ans. 0

Q4. What is the index value of last element of a string?

Ans. -1

Q5. If the length of the string is 10 then what would be the positive index value of last element?

Ans. 9
66

Q6. If the length of string is 9, what would be the index value of middle element?
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans. 4

Q7. Index value of a string can be in float. (T/F)

Ans. False

Q8. What type of error is returned by following statement, if the length of string 'str1' is 10.

print(str1[13])

Ans. Index error

Q9. Write the output of the following:


str1 = "Welcome to my Blog"

a. print(str1[-1])
b. print(str1[9])

Ans
g
o

Q10. Write a code to assign a string "Hello World"' to a string variable named "str1".

Ans. str1 = "Hello World"

String in Python
Practice Questions of String in Python – Test 4
Q1. Write a program to display each character of the following string in separate line using 'for' loop.
str1 = Welcome to My Blog

Ans.
str1 = "Welcome to my Blog"
for i in str1:
print(i)
67

Q2. Write a program to display each character of the following string in separate line using 'while' loop.
str1 = Welcome to My Blog
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans.
str1 = "Welcome to my Blog"
c=0
while c <len(str1):
print(str1[c])
c=c+1

Q3. Index value of string "str1" varies from 0 to len(str1)-1. (T/F)


Ans. True

Q4. Write the positive and negative index value of 'B' in the following string.
"Welcome to my Blog"

Ans. positive index of B is = 14


negative index of B is = -4

Q5. What do you mean by concatenation of string?


Ans. Joining of two or more string is called concatenation. for example
a = 'Amit'
b = 'Sethi'
c=a+b

Q6. Which of the following is an example of concatenation?

a. 6 + 3
b. '6' + '3'
c. 'a' + 'b' + 'c'

Ans. b and c

Q7. Write a program to count the length of string without using inbuilt function.
Ans.
str1 = "Welcome to my Blog"
c=0
for i in str1:
c=c+1

print("length of string is", c)


68

Q8. Write the output of the following statement.


Page

str1 = "Welcome to my Blog"

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


for i in str1:
print(i)
print(i, end =' ')
print(i, end = '#')

Ans.
A
A A#m
m m#i
i i#t
t t#

Q9. Write the output of the following statement.

str1 = "Amit"
for i in str1:
print(i)
print(i, end =' ')

Ans.
A
Am
mi
i t
t

Q10. Write the output of the following statement.

str1 = "Welcome to my Blog"


for i in str1:
print(i)
print(i, end =' ')
print(i, end = '#')
69

Ans.
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


A m
m i
i t
t t#

Practice Questions of String in Python – Test 5


Q1. Match the Following

Column-1 Column-2

Slicing string[range] + ‘x’

Concatenation string[: – 1]

Repetition string[range]

Membership string1 + string2

Reverse in, not in


Solution
Column-1 Column-2

Slicing string[range]

Concatenation string1 + string2

Repetition string * 7

Membership in, not in

Reverse string[: – 1]
Q2. Write the code to join string 'str1' and 'str2' and store the result in variable 'str3'
Ans. str3 = str1 + str2

Q3. The ___________ operator join the string.


Ans. +

Q4. What type of error is shown by following code?


70

>>> 2 + '3'
Page

Ans. TypeError

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q5. Which operator is used to replicate string?
Ans. *

Q6. Write the output of the following.


>>> 'A' * 3
Ans. AAA

Q7. Write the output of the following:

for i in range(2,5,2):
print(i * '@')

Ans.
@@
@@@@

Q8. 'in' or 'not in' are the _________ operator


Ans. Membership

Q9. Write the output of the following


>>> 'h' in 'Hindi'
>>>'i' in 'Hindi'
Ans.
False
True

Q10. Write the output of the following


for i in "Amit":
print(i in "Amit")

Ans
True
True
True
True
71

Practice Questions of String in Python – Test 6


Q1. Write the output of the following
Page

>>>"string" in "substring"

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


>>>"string" not in "substring"
Ans.
True
False

Q2. Write the output of the following:


>>>'tie' == 'ties'
>>>"Amit" != "Amitabh"
>>>"amit" > "Amitabh"
Ans.
False
True
True

Q3. Write the full form of ASCII


Ans. American Standard Code of Information Interchange

Q4. Write the ASCII value of 'A' and 'a'.


Ans. A = 65, a = 97

Q5. String Slicing is used to fetch substring from a string. (T/F)


Ans. True

Q6. Write the output of the following.


S = "Welcome to my Blog"
print(S[2 : 3])
print(S[2 : 10])
print(S[-2 : ])
print(S[-10 : -2 : 2])

Ans
l
lcome to
og
t yB
72

Q7. Strings are mutable.(T/F)


Ans. False
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q8. Write the output of the following
>>>str1 = "Anita"
>>>str1[1] = 'm'
>>>print(str1)
Ans. TypeError

Q9. Name any two built in function associated with string.


Ans. len() and capitalize()

Q10. Which function of string return the numerical value?


Ans. len()

Practice Questions of String in Python – Test 7


Q1. What is the value returned by find() function for an unsuccessful search?
Ans. -1

Q2. isalpha() returns True if the string contains only alphabet.(T/F)


Ans. True

Q3. Write the output of the following


str1 = "Amit"
str2 = "My Blog"
str3 = "#blog"
str4 = "My 1st Blog"
print([Link]())
print([Link]())
print([Link]())
print([Link]())

Specify the reason if any of the above print statement return False.
Ans.
True
False : Return False as str2 conains spaces
False : Returns False as str3 contain special character
False : Return False as str4 contain digit and spaces.
73

Q4. Write a program to accept string and display total number of alphabets.
Ans.
Page

str1 = input("Enter any string")


S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
c=0
for i in str1:
if [Link]()==True:
c = c+ 1
print("Total number of alphabets are", c)

Q5. Write a program to accept a string and display the sum of the digits, if any present in string.
for example:
input string : My position is 1st and my friend come on 4th
output : 5

Ans:
str1 = input("Enter any string")
n=0
s=0
for i in str1:
if [Link]() == True:
n = int(i)
s = s+n
print(sum of the diit is ", s)

Q6. Write the output of the following:


>>>a = 123
>>>b = "123"
>>>[Link]()
>>>[Link]()

Ans
True
Error

Q7. What is the difference between lower() and islower()?


Ans. lower() function converts the given string in lowercase while islower() check whether given string is
in lowercase r not.

Q8. Write a program to accept a string and convert it into lowercase.


Ans.
74

str1 = input("Enter any string")


print([Link]())
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q9. Write a program to count the number of lowercase and uppercase character in a
string accepted from the user.
Ans.
str1 = input("Enter any string")
for i in str1:
if [Link]()==True:
l = l+1
if [Link]() == True:
u = u+1
print("Total uppercase characters are--",u)
print("Total lowercase characters are--",l)

Q10. Write the output of the following:


>>>s = "My blog"
>>>[Link]()
>>>[Link]()
>>>[Link]()
>>>[Link]()
>>>[Link]()
>>>[Link]()
Ans.
MY BLOG
my blog
False
False
False
False

Practice Questions of String in Python – Test 8


Q1. What is lstrip () function in String?
Ans. lstrip() function simply remove the spaces or specified characters from the left of the string.

Q2. Write the output of the following.(# represents the spaces)


>>>str1 = "Welcome to my Blog"
>>>print(len(str1))
>>>str2 = "###Welcome to my Blog"
>>>print(len(str2))
75

>>>print(len([Link]()))
Ans.
Page

18
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
21
18

Q3. Write the output of the following.(# represents the spaces)


>>>str2 = "###Welcome to my Blog####"
>>>print(len(str2))
>>>print(len([Link]()))
>>>print(len([Link]()))
Ans.
25
18
21

Q4. Write the output of the following.


>>>str1 = "Welcome to my Blog"
>>>print([Link]('og'))
>>>print([Link]('We'))
>>>print([Link]('Welog))
Ans.
Welcome to my Bl
lcome to my Blog
lcome to my B

Q5. Write the output of the following.


>>>print(len([Link]('og')))
>>>print(len([Link]('We')))
>>>print(len([Link]('Welog)))
Ans
16
16
13

Q6. isspace() returns True if the string contain only spaces (T/F)
Ans. True

Q7. Write the output of the following


>>>s1 = " "
76

>>>s2 = " Amit"


>>>print([Link]())
Page

>>>print([Link]())
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Ans.
True
False

Q8. Define the following function with example


a. istitle()
[Link]()
Ans.
istitle() - This function returns True if the string is in titlecase only otherwise returns False.
for example
s = "Welcome To My Blog"
print([Link]())
The above code returns True as the string 's' is in Title case.

swapcase() - This function converts all the lowercase characters to uppercase and vice versa
for example
s = "Welcome To My Blog"
print([Link]())

Output: wELCOME tO mY bLOG

Practice Questions of String in Python - Test 9

Q1. Write the output of the following:


str1 = "Welcome to my Blog"
a. print(len(str1))
b. print(capitalize(str1))
Ans.
a. 18
b. Welcome to my blog

Q2. Write the output of the following.


>>>str1 = "Welcome to my Blog"
>>>x = [Link]()
>>>print(x)
Ans.
['welcome', 'to', 'my', 'blog']
77

Q3. Write a program to accept a string and display each word and it's length.
Ans.
Page

str1 = input("Enter any String")


S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
x = [Link]()
for i in x:
print(i, "------", len(i))

Q4. Write a program to accept a string and display string with capital letter of each word.
for example, if input string is : welcome to my blog
output string : Welcome To My Blog
Ans.
str1 = input("Enter any String")
x = [Link]()
str2 = " "
for i in x:
str2 = str2 + " " + [Link]()
print(str2)

Q5. What is split() function in String?


Ans. split() function split or break the string into multiple substring at specified separator.

Q6. Write the output of the following:


a = "Mummy?Papa?Brother?Sister?Uncle"
print([Link]())
print([Link]('?')
print([Link]('?',1)
print([Link]('?',3)
print([Link]('?',10)
print([Link]('?',-1)

Ans.
['Mummy?Papa?Brother?Sister?Uncle']
['Mummy', 'Papa', 'Brother', 'Sister', 'Uncle']
['Mummy', 'Papa?Brother?Sister?Uncle']
['Mummy', 'Papa', 'Brother', 'Sister?Uncle']
['Mummy', 'Papa', 'Brother', 'Sister', 'Uncle']
['Mummy', 'Papa', 'Brother', 'Sister', 'Uncle']

Q7. Write a program to replace all the word 'do' with 'done' in the following string.
str1 = "I do you do and we all will do"
78

Ans.
str1 = "I do you do and we all will do"
Page

print([Link]('do','done'))
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Q8. Write the output of the following.
str1 = "I went to Auli"
print([Link]("Auli", "Leh"))
print(str1)
Ans.
I went to Leh
I went to Auli

Q9. What is the purpose of find() function in string?


Ans. find() function will return the first occurrence of substring in main string.

Q10. Write the output of the following:


str1 = "Welcome to my Blog"
print([Link]('o'))
print([Link]('o',3))
print([Link]('o',7))
print([Link]('o',7,10))
Ans.
4
4
9
9
Practice Questions of String in Python – Test 10
Q1. Accept a string and display in reverse order.
Ans.

str = input("Enter any String")


print(str[: : -1])
Q2. Write a program to accept a string and display 20 times.
Ans.

str = input("Enter any String")


for i in range(20):
print(str)
Q3. Write a program to accept a string in python and display the entire string in upper case.
79

Ans.
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


str = input("Enter any String")
print([Link]())
Q4. Write a program to accept a string and display last three characters of the string.

Ans.
str = input("Enter any String")
print(str[-3 : : 1])
Q5. Write a program to accept a string in python and display the entire string in lower case.

Ans.

str = input("Enter any String")


print([Link]())
Q6. Accept a string and display the entire string with first and last character in upper case.

Ans.

str = input("Enter any String")


print(str[0].upper() + str[1:-1] + str[-1].upper())
Q7. Write a program to accept a string and display first three characters of the string.

Ans.

str = input("Enter any String")


print(str[0:3])
Q8. Write a function in python which accept a string as argument and display total number of vowels.

Ans.

def vowcount(str):
v=0
for i in range(len(str)):
if str[i] in "aeiouAEIOU":
80

v = v +1
Page

print("Total number of vowels are ", v)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q9. Write a function in python which accept a string as argument and display total number of lower
case characters.

Ans.

def lowercount(str):
l=0
for i in range(len(str)):
if str[i].islower( ):
l = l +1
print("Total number of lower case are ", l)
Q10. Write a function in python which accept a string as argument and display total number of digits.

Ans.
def digitcount(str):
d=0
for i in range(len(str)):
if str[i].isdigit( ):
d = d +1
print("Total number of digits are ", d)

81
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Text File Handling in Python Handout –
Part 1
What is File?
A file is a document which can be read, written according to the
requirement. Every File has a unique name. In other words we can
say that file is a collection of bytes which is stored in a secondary
storage like hard disk, pen drive etc.
Why File?
As file store the data permanently, which can be accessed even
after closing the program. Like we create a file in MS word, Power
point etc. so that we can access the data later when required.
Types of File: There are two types of file
1. Text File
2. Binary File
Difference between Text file and Binary File.
Text File Binary File

These files can be read by human directly These files can not be read by humans directly.

Each line is terminated by a special character ,


No delimiter for a line
known as EOL

Processing of file is slower than binary file Processing of file is faster than text file
open( ) and close( ) functions :
The first step to work with a file is to open a file. We can open a file
by using open( ) function. open() function takes two arguments.
1. Name of the file
2. Access mode
Syntax to open a file
file handle/file object = open(“file name”, “access mode”)
NOTE: By default access mode is read mode
Let we take an example. Suppose there is a file named “[Link]” is
to be open for reading then the code will be as follows.
f = open (“[Link]”, “r”)
Explanation of above code :
1. ‘f’ is file object or file handle ( A file object is reference to file
by which we can read and write in file)
2. open( ) function is used to open a file named “[Link]”
3. “r” is read mode. In this mode we can read the contents.
Modes for opening a file:
82

 Read : This mode is to read the content of the file. It is denoted


Page

by symbol “r”

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


 Write : This mode is used to write the content on the file. It
over writes the previous content. It is denoted by symbol “w”.
 Append : This mode is used to add the data in the existing
content of the file.
Text File Handling in Python Handout (Question Answer Session.)
Q1. What is the difference between the write and append mode?
Q2. f = open("[Link]")
The above file will open in _______________ mode.
Q3. f = open("[Link]", "w")
The above statement will return any error, if the file "[Link]" does
not exist.
Q4. What error is returned by the following code, if the file does not
exist.
f=open("[Link]", "r")
Types of File Modes
r : open file in read mode. This is the default mode
r+ : open the file in reading and writing mode means we can read
the data as well as write the data.
This also return error if file does not exist.
w : This mode will open file in write mode. This mode will create a
new file, if file does not exist. This
mode will over writes the existing content.
w+ : This mode open the file in writing and reading mode.
a : This mode will open file in append mode. This mode will add data
at the end of the file. The file
pointer is present at the end of the file.
a+ This mode is for both appending content and reading content.
Note :
 File should be saved in the same folder where python is saved,
otherwise we need to give complete path for example if the file
“[Link]” store in a folder “senior” in D drive so we can open
file in read mode by the following two ways.
1. f = open(“D:\\senior\\[Link]”,”r”)
2. f = open(r,”D:\senior\[Link]”, “r”)
 Giving extension to the file is not mandatory like we can open
file f = open (“data”, “r”) will also work
Text File Handling in Python Handout (Question Answer Session.)
Q1. Is there any difference between the following statements?
f = open("[Link]") and f = open("[Link]", "r")
Q2. Write the code to open a file "[Link]" which is stored in folder
named "demo"
83

in C drive.
Q3. Where the file pointer present when we open file in the
Page

following mode

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


1. Read mode
2. Write mode
3. Append mode
File Handling – Part 1
Properties of File Object.
A file object or file handle is the reference of a file which helps to do
various task on file. It has various properties like:
1. name : It displays the name of the file
2. mode : It displays the mode of file(in which mode it is opened)
3. closed : It displays whether the file is closed or not. It return
False if the file is open and True if the file is closed.
4. readable() : It displays whether the file is readable or not.
for example

Output of the above program will be


[Link]
w
False
False
Functions for Reading File:
Reading file help us to play with the character, word or lines of a
file. There are many methods or functions in python which help us to
read data from file. We will discuss one by one
1. read() : This function is used to read the entire content of file.
for example:
f = open("[Link]", "r")
d = [Link]( )
The first line of code will open the file [Link] in read mode and the
second line will read the entire content and transfer/store data in
variable d in the form of String.
2. read(n) : This function will read the first n character from the file .
for example
84

f = open("[Link]", "r")
Page

d = [Link](5)

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


The above code will print the first five character from the file.
Q1. Write the output of the following code
f = open("[Link]", "r")
d =read()
d1 = read(5)
print(d)
print(d1)

#data file contains the following data


Welcome to [Link]
3. readline() : This function will read one line at a time from the file
Syntax of using readline() is
f = open("[Link]", "r")
d = [Link]()
print(d)
The above code will read and print first line from the file. To read
the entire content of file, we need to use the loop.
f = open("[Link]", "r")
for i in f:
print(i)
4. readlines() : This function is used to read all the lines from the
file. This method will return a list of strings, each separated by \n.
f = open("[Link]", "r")
d = [Link]()
print(d)
Text File Handling in Python Handout (Question Answer Session.)
Q1. What is the difference between read() and read(n) function?
Q2. How readline() is different from readlines()?
Q3. Write a program to read the frequency of alphabet 'a' in file.
Q4. Write a program to count the total number of characters in a
file.
Q5. Write four properties of file objects.

85
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Solution of Q 3

Solution of Q 4

File Handling – Part 2

Text File Handling in Python Handout –


Part 2
Writing to File
We can write data into our file with the help of programs in python.
When we open file in write mode and file does not exist then this
mode will create a new file.
There are two functions in python which help us to write data into a
file.
1. write(string) : This method takes a string as parameter and
write the same string into our file. This method does not add
EOL (End of Line) character automatically. We have to add ‘\n’
character after each line. This method takes only string as
argument so if you want to add numbers in file then first we
need to convert the number into string.
f = open("[Link]", "w")
86

[Link]("welcome to my site")
[Link]("[Link]")
Page

[Link]()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Output of the above code

NOTE : Don’t Forget to write the close() method at the end of the
code
To display the above text in separate lines we need to add “\n” at
the end of first line.
f = open("[Link]", "w")
[Link]("welcome to my site\n")
[Link]("[Link]")
[Link]()
Output of above code

Q1. Write a program to accept age from the user and write in a file
“[Link]” like below:
“Your age is 34”
Ans.

f = open("[Link]", "w")
age = input("Enter your age")
[Link]("Your age is ")
[Link](age)
[Link]()
2. writelines() : This method is used for writing the sequence data type like
list, tuple or string into a file.
Syntax of writelines()
[Link](sequence)
Q2. Write a program to write names of five friends in a file
“[Link]” by using write() as well as writelines() method.
87

f=open("[Link]","w")
[Link](["Amit\n","Sumit\n","Anil\n","Naina\n","Ananya\n"])
Page

[Link]()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Output of above program
Amit
Sumit
Anil
Naina
Ananya
Point to remember : If we don’t use “\n” in above program then the
names will be displayed in same line.
The above program can also be done by using write() method.
f=open("[Link]","w")
[Link]("Amit\n")
[Link]("Sumit\n")
[Link]("Anil\n")
[Link]("Naina\n")
[Link]("Ananya\n")
[Link]()
Point to remember : When we have to write a list, tuple we will use
writelines() instead of write(). For string, we can use any function
either write() or writelines().
Text File Handling in Python Handout (Question Answer Session.)
Q1. Write a program to write the following lines in the same format
in a file "[Link]" (using write()
as well as writelines() method)

Welcome to
my website
[Link]

Q2. What is the difference between write() and writelines() method?


Q3. write mode creates a new file, if file does not exist. (T/F)
Q4. Write a program to accept Roll number and name of five
students from the user and write on
a file "[Link]"
Q5. Write a program to find the length(number of characters) of the
file "[Link]".
SOLUTIONS
Ans1.
f=open("[Link]","w")
[Link]("Welcome to\n")
[Link]("my website\n")
[Link]("[Link]\n")
88

[Link]()
Page

OR

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


f=open("[Link]","w")
[Link](["Welcome to\n","my website\
n","[Link]\n"])
[Link]()

Ans2.
write() method is used to write string in file while writelines() is
used to write list in a file.

Ans3. True

Ans4.
f=open("[Link]","w")
[Link]("Roll number")
[Link]("\t\t")
[Link]("Name")
[Link]("\n")
for i in range(5):
rn=input("Enter roll number")
nm = input("Enter name")
[Link](rn)
[Link]("\t\t\t")
[Link](nm)
[Link]("\n")
[Link]()

Execution and output of the above program is shown below

89

Ans 5.
Page

f=open("[Link]","r")

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


d = [Link]()
print("Length of file is", len(d))
With Statement
Till now we have done many programs and in each programs we
have used the following functions.
 open()
 close()
we can close the file without using close() function or we can say
that file automatically closed and that can be achieved by using
“with” statement.
Demonstration of “with” Statement in the following program
with open("[Link]", "w") as f:
[Link]("Welcome to\n")
[Link]("my website\n")
[Link]("[Link]")
In the above program we have not called the close() function, the
file will automatically closed.
Text File Handling in Python Handout –
Part 3
Appending to File
When we want to add more data into a file which already contains
some data then we use this append mode. When we open the file in
append mode then the following thing happens
1. It opens the file with file pointer at the end of the file.
2. If the file does not exist then this mode create a new blank file
with pointer in the beginning.
NOTE: In simple words we can understand that append means
adding data to a file without erasing the existing content.
Syntax of opening file in append mode
f = open("[Link]", "a")
The above code will open a file “[Link]” in append mode with ‘f’ as
a file handle/object.
Understand the concept of Append
Step 1: Open a file and write something
f = open("[Link]"
[Link]("Welcome to my site\n")
[Link]("[Link]\n")
[Link]()
Output of above program
90
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Step 2 : Open a file to add some more data to the above file.
f = open("[Link]", "a")
[Link]("File Handling handout part - 1\n")
[Link]("File Handling handout part - 2\n")
[Link]()
Output of above program

NOTE : In above code when we open file in append mode, it did not
erase the existing content and , moreover, added the new content
at the end of file.
Text File Handling in Python Handout (Question Answer Session.)
Q1. What do you mean by append mode?
Ans. Append mode is to add new content to a file without erasing
the

Q2. Both append and write mode create a new file, if file does not
exist.(T/F)
Ans. True

Q3. Write a program to append the following lines in file "[Link]"


"Subscribe to my site"
"Text File Handling in python Handout"
"Text File Handling in python Handout is a complete tutorial"
Ans.
f = open("[Link]" , "a")
[Link]("Subscribe to my site\n")
[Link](""Text File Handling in python Handout\n")
91

[Link](""Text File Handling in python Handout is a complete


tutorial\n")
Page

[Link]()

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Q4. What is the difference between a and a+ mode?
Ans. 'a is 'append mode which means we can add new content to a
file without erasing the existing
content while 'a+' is append as well as read mode, means we can
write new content as well as read
content from file.

Q5. Write a program to write the following data in a file "[Link]"


in the same format as shown
below.
Roll No. Name
1 Amit
2 Sumit
3 Naina

Answer 5.

Text File Handling in Python Handout (Question Answer Session.)


Q1. Write a program to write the following text in file named
"[Link]"

Welcome to Text File Handling in python Handout


Text file handling in python handout is a complete
tutorial
I love text file handling in python handout
92

How do you like text file handling in python


Page

handout

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]


Ans.
f = open("[Link]", "w")
[Link]("Welcome to Text File Handling in python Handout\n")
[Link]("Text File Handling in python Handout is a complete tutorial\
n")
[Link]("I love text File Handling in python Handout\n")
[Link]("How do you like text file handling in python handout")
[Link]()

Q2. Write a program to read the above created file and display the
content.
Ans. Do it yourself

Q3. Write a program to display the following in the file "[Link]"


(created above)
1. Number of Vowels
2. Number of Words
3. Number of Spaces
4. Frequency of alphabet 'a'
5. Frequency of word "Text"
Ans. Do it your self

93
Page

S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]

You might also like