Python Error Finding Questions
Python Error Finding Questions
com/important-practice-questions-of-list-in-python/
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:
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.
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
4
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
7
Page
Ans. a = list(“Practice”)
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
print(list2[ ? ])
Page
print(list2[ ? ])
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
['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
['o', 't']
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
Ans 1 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)
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.
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
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. 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
Q1. Write a program to check whether a number (accepted from user) is present in a list.
20
Page
1. push (4)
2. push (7)
3. push ("a")
4. push ("Suman")
In the form of List the above stack will be represented as shown below
2. Adding an element to a Stack : We can add element in a stack by using append( ) function as shown
below
Page
Structure in Python.
Page
st=[ ]
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
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
>>> y = 7
>>> print(x + y )
Ans
a. 12
b. 32
Q6. Write one drawback of interactive mode.
Ans.
penc = 7
er = 5
totcost = penc * 5 + 2 * er
29
Ans. # symbol
Q10. What do you mean by variable?
Ans. Variables are used to store values which we can use later in our programs.
Ans. id command is used to find the address of variable for example, to find the address of variable ‘x’
code is
>>>id(x)
Ans. Data type refers to the type of value used for example integer, float string etc
Ans. True
Q8. Which data type store the combination of real and imaginary numbers?
Ans. Complex
Ans.
47000000
390
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. False
Q6. Write the code to display all keywords in python.
Ans. [6, 2, 3]
Q10. Name three types of operators in python.
>>> v1 = 10
>>> v2 = None
>>> v1
>>> v2
>>>print(v2)
Ans.
10
None
Ans. This function tell us about the data type of a variable. for example
a = 10
print(type(a))
OUTPUT : <class 'int'>
>>> type(10)
Page
>>>type('10')
>>>type(True)
>>>type('False')
<class 'str'>
<class 'float'>
<class 'bool'>
<class 'str'>
Q9. Identify the variable name, variable type, value and operator used in the following statement.
34
>>> x = 9
Page
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
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
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
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
False
True
False
True
False
38
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
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
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
Q6. Write a user defined function to print "Python Fundamentals" five times.
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.
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
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)
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)
Ans.12
44
Page
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
[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")
[9]:
for i in range(7,-2,-9):
for j in range(i):
print(j)
46
0
Page
[10]:
i="9"
for k in i:
print(k)
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):
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
[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
[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)
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
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
[30]:
print((3>1) and (9<1))
False
True
[32]:
f=0
while(f<10):
print(f)
f=f*3
1@2@3@3@4@6@4@5@7@10@3
52
[34]:
i=0
Page
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
[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
while(x<15):
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
[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")
while(a<=10):
print("a")
a+=1
56
a
Page
[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
for x in range(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
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
[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
Ans.
AMIT
AMIT
AMIT
60
AMIT
Page
[63]
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
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
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.
Welcome to my Blog
Welcome to
my Blog
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
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
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
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. Traversing a string means accessing all the elements of the string one by one by using index value.
Ans. 0
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
Ans. False
Q8. What type of error is returned by following statement, if the length of string 'str1' is 10.
print(str1[13])
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".
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
Q4. Write the positive and negative index value of 'B' in the following string.
"Welcome to my Blog"
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
Ans.
A
A A#m
m m#i
i i#t
t t#
str1 = "Amit"
for i in str1:
print(i)
print(i, end =' ')
Ans.
A
Am
mi
i t
t
Ans.
Page
Column-1 Column-2
Concatenation string[: – 1]
Repetition string[range]
Slicing string[range]
Repetition string * 7
Reverse string[: – 1]
Q2. Write the code to join string 'str1' and 'str2' and store the result in variable 'str3'
Ans. str3 = str1 + str2
>>> 2 + '3'
Page
Ans. TypeError
for i in range(2,5,2):
print(i * '@')
Ans.
@@
@@@@
Ans
True
True
True
True
71
>>>"string" in "substring"
Ans
l
lcome to
og
t yB
72
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
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)
Ans
True
Error
>>>print(len([Link]()))
Ans.
Page
18
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
21
18
Q6. isspace() returns True if the string contain only spaces (T/F)
Ans. True
>>>print([Link]())
S. SHUNMUGA SUNDARAM , M.E/CSE, AMIE, MISTE [Link]
Ans.
True
False
swapcase() - This function converts all the lowercase characters to uppercase and vice versa
for example
s = "Welcome To My Blog"
print([Link]())
Q3. Write a program to accept a string and display each word and it's length.
Ans.
Page
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)
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
Ans.
Page
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.
Ans.
Ans.
Ans.
def vowcount(str):
v=0
for i in range(len(str)):
if str[i] in "aeiouAEIOU":
80
v = v +1
Page
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
These files can be read by human directly These files can not be read by humans directly.
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
by symbol “r”
in C drive.
Q3. Where the file pointer present when we open file in the
Page
following mode
f = open("[Link]", "r")
Page
d = [Link](5)
85
Page
Solution of Q 4
[Link]("welcome to my site")
[Link]("[Link]")
Page
[Link]()
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]()
Welcome to
my website
[Link]
[Link]()
Page
OR
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]()
89
Ans 5.
Page
f=open("[Link]","r")
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
[Link]()
Answer 5.
handout
Q2. Write a program to read the above created file and display the
content.
Ans. Do it yourself
93
Page