0% found this document useful (0 votes)
58 views35 pages

Python Programming Quiz Questions

The document contains multiple choice and short answer questions related to Python programming, covering topics such as data types, operators, functions, and string manipulation. It includes answers to the multiple choice questions and provides explanations for various Python concepts. The document serves as a study guide for understanding Python programming fundamentals.

Uploaded by

priya
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)
58 views35 pages

Python Programming Quiz Questions

The document contains multiple choice and short answer questions related to Python programming, covering topics such as data types, operators, functions, and string manipulation. It includes answers to the multiple choice questions and provides explanations for various Python concepts. The document serves as a study guide for understanding Python programming fundamentals.

Uploaded by

priya
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

Multiple Choice Questions

1. Which of the following is not a data type?

a. String b. Numeric

c. Array d. Tuples

2. Which character is used for commenting in Python?

a. # b. !

c. @ d. *

3. What is the output of [‘name!’] * 2?

a. [‘name!’] * 2 b. [‘name’!, ‘name’!]

c. [‘name!’, ‘name!’] d. [‘name’!] * 2

4. Which is not a reserved keyword in Python?

a. InserT b. Pass

c. Class d. Lambda

5. What is the output of >>> 4+?

a. 4+ b. 4

c. 5 d. Invalid syntax

6. What will be the output of str[0:4] if str=”Hello”?

a. ‘Hello’ b. ‘H’

c. ‘Hel’ d. ‘Hell’

7. Which of the following is the floor division operator?

a. / b. %

c. // d. \\

8. Which of the following is used to find the first index of


search string?

a. .find(“string”) b. .search(“string”)
c. (“string”).find d. (“string”).search

9. Which of the following is used to access single character of


string?

a. [:] b. ()

c. [.] d. []

10. What is the order of precedence in Python?

i. Addition ii. Multiplication

iii. Division iv. Subtraction

v. Exponential vi. Parenthesis

a. ii, i, iii, iv, vi, v b. vi, v, iii, ii, i, iv

c. vi, v, ii, i, iii, iv d. ii, vi, iii, i, iv, v

11. Which of the following will be printed?

x =4.5

y =2

print x//y

a. 2.0 b. 2.25

c. .25 d. 0.5

12. What gets printed?

Nums=set([1,1,2,3,3,3,4])

Print len(nums)

a. 2 b. 4

c. 5 d. 7

Answers to Multiple Choice Questions

1. c 2. a 3. c 4. a 5. d 6. a 7. c 8. a 9. d 10. b
11. a 12. B

Short Questions

1. What is Python? What is Python good for?

2. How can we distinguish between tuples and lists?

3. How can a string be converted to a number?

4. What are comments in Python?

5. What will be the output of the given code?

list = [‘p’, ‘r’, ‘s’, ‘t’,]

print list[8:]

6. Briefly describe the data types in Python.

7. What will be the output of the code str + “Python” if str =


‘Programming!’?

8. What will be the output of the code test*5 if test = (000,


‘computer’)?

9. Describe operators in Python.

10. How will you create a dictionary in Python?

11. How will you convert a string to an integer in Python?

12. What are the uses of //, **, *= operators in Python?

13. What are comments?

Ans. Comments are annotations made by the programmer.


These help other programmers in understanding the code.

14. Which character is used for commenting in Python?

Ans. Hash mark (#) is used for commenting in Python.


15. What are data types?

Ans. The data you have to manipulate can be in different


forms. For example, the name of a person is in string form
while his age is in numeric form.

16. What is a list?

Ans. A list is a dynamic array or sequence that is ordered,


indexable and mutable. It is one of the most versatile
compound data types of Python. A list is used to store multiple
items separated by commas within square brackets [].

17. What is the output of print list[2] when list = [‘abcd’, 2.23,
‘john’]?

Ans. john

18. What is the main difference between a list and a tuple?

Ans. In a list, items are enclosed within square brackets; tuple


is a sequence of items separated by comma and enclosed in
parentheses.

19. What are the different types of operators in Python?

Ans.

● Arithmetic Operator

● Comparison Operator

● Assignment Operator

● Logical Operator

● Bitwise Operator

● Membership Operator

● Identity operator

20. What is slicing?


Ans. In Python, you can extract a substring by using a colon
inside the square bracket [:]. The resultant substring is a part
of the long string.

21. What are statement and expression in Python?

Ans. A statement is the instruction that can be interpreted by


the Python interpreter. An expression is a combination of
variables, operators, values and reserve keyword.

22. Write a while statement that prints integers from zero to 5.

>>> count = 0

>>> while count < 6:

print count

count += 1

0 # Output

23. What is a for statement?

Ans. The for statement in Python differs a bit from what you
may be used to in C. In C, for loop gives the user the ability to
define both the iteration step and the halting condition, but in
Python, the for statement iterates over the items any ordered
sequence (a list or a string), in the order that they appear in
the sequence.

24. What is the syntax for ifelse and elif statements?

Ans.
if expression1 :

statement(s)

elif expression2 :

statement(s)

elif expression3 :

statement(s)

else expression4 :

statement(s)

● Python supports six data types which are as follows:

1. Numeric

2. String

3. List

4. Tuple

5. Dictionary

6. Boolean

25. What is a function?

Ans. Functions are self-contained programs that perform some


particular tasks. Once a function is created by the
programmer, this function can be called anytime to perform
the specific task.

26. What is Type conversion?

Ans. These are some built-in functions in the Python


programming language that can convert one type of data into
another type. For example, the int function can take any
number value and convert it into an integer.

27. Give the syntax required to convert an integer number into


string and a float to an integer.
Ans. #integer to string

>>>str(5)

‘5’ # Output

# float to integer

>>>float(5.50)

5 # Output

28. What are mathematical functions? How are they used in


Python?

Ans. Python provides us a math module containing most of the


familiar and important mathematical functions. A module is a
file that contains some predefined Python codes. A module can
define functions, classes and variables. It is a collection of
related functions grouped together.

Before using a module in Python, we have to import it.

For example, to import the math module, we use:

>>> import math

29. Write a program to print the calendar for the month of


March, 1991.

Ans.

>>> import calendar

>>> c = [Link](1991, 3)

>>> print c

March 1991

30. Write the syntax for defining a function.

Ans. deffunctionname(parameters):

“function_docstring”
statement(s)

return [expression]

31. Write a function which accepts two numbers and returns


their sum.

Ans. >>>def sum(arg1,arg2):

... sum = arg1 + arg2

... return sum

# Now calling the function here

>>> a = 4

>>> b = 3

>>>total = sum(a,b) # calling the mult function

>>>print(total)

32. Define the return statement in a function. Give the syntax.

Ans. The return statement is used to exit a function. A function


may or may not return a value. If a function returns a value, it
is passed back by the return statement as argument to the
caller. If it does not return a value, we simply write return with
no arguments.

Syntax

return [expression]

Multiple Choice Questions

1. What are the advantages of using functions?

a. b. Clarity of code

c. d. All
2. Which keyword is used to define the block of statement in
the function?

a. Function b. def

c. func d. pi

3. What does the block of statement always starts with?

a. (:) b. (;)

c. [:] d. [;]

4. Which file contains the predefined Python codes?

a. Function b. Pi

c. module d. lambda

5. A function is called using the name with which it was


defined earlier, followed by:

a. { } b. ()

c. <> d. [ ]

6. What is the use of the return statement?

a. exit a function b. null value

c. initiate a function d. none

7. Which keyword is used to create an anonymous function?

a. Def b. lambda

c. func d. pi

8. What does the following code do?

def p(q, r, s): pass

a. defines a function, which does nothing b. defines an


empty list
c. defines a function with parameter d. defines an
empty string

9. Which command cannot be called directly by an anonymous


function?

a. Scan b. Def

c. exit d. print

10. What will be the output of the following code?

definputDevice():

print(‘Keyboard’)

inputDevice()

inputDevice()

a. ‘Keyboard’ ‘Keyboard’ b. ‘Keyboard’

c. Keyboard Keyboard d. Keyboard

11. What will be the output of the following code?

defsqr(a):

return a * a

a = sqr(4)

a. 4 b.

c. 8 d. none

Answers to Multiple Choice Questions

1. d 2. b 3. a 4. c 5. b 6. a 7. b 8. a 9. d 10. c

11. b

1. What is a String in Python?


Ans. Strings are one of the most popular data types in Python.
Strings are created by enclosing various characters within
quotes. Python does not distinguish between single quotes and
double quotes.

2. What is the work of len function? Give one example.

Ans. len is a built-in function in Python programming


language. When used with a string, len returns the length or
the number of characters in the string.

>>> x = ‘My name is Anil’

>>> len(x)

15

3. What do %s, %d, %x and %e stand for?

Ans. %s = String conversion via str() prior to formatting

%d = Signed decimal integer

%x = Hexadecimal integer (lowercase letters)

%e = Exponential notation (with lowercase ‘e’)

4. What is a list? How are the values of a list accessed?

Ans. Just like a string, a list is also a series of values in Python.


In a string, all the values are of character type, but in lists,
values can be of any type. The values in a list are called
elements or items. A list is a collection of items or elements;
the sequence of data in a list is ordered and can be accessed
by their positions, i.e., indices.

Example

>>> list = [1,2,3,4]

>>> list[1]

2 # Output

>>> list[3]
4 # Output

5. What do you mean by “Lists are mutable”?

Ans. Lists are mutable means that we can change the value of
any element inside the list at any point of time. The elements
inside the list are accessible with their index value. The index
will always start with 0 and end with n-1, if the list contains n
elements.

Example

>>> list = [1,2,3,4]

>>> list[2] = 6

>>> print list

[1,2,6,4] # Output

6. What is the pop operator?

Ans. If the index of the element we want to delete is known, we


can use the pop operator. The pop operator deletes the
element on the provided index and stores that element in a
variable for further use.

7. What are concatenation operator and in operator?

Ans. Concatenation Operator:

The concatenation operator works in the same way in lists as it


does in strings. This operator

concatenates two strings. Concatenation is done by the +


operator in Python.

in Operator:

The in operator works on lists. It tells the user whether the


given string exists in the list or not.

It gives a Boolean output, i.e., True or False. If the given input


exists in the string, it gives True as output, otherwise, False.
8. Give examples for len, max and min methods.

Ans. >>> list = [789, ‘abcd’,’jinnie’,1234]

>>> len(list)

4 # Output

>>> max(list)

‘jinnie’ # Output

>>> min(list)

789 # Output

Multiple Choice Questions

1. Which type of operator will we use to access a part of the


string?

a. { } b. [ ]

c. <> d. ( )

2. What will be the output of the given code?

>>>”h”+”lm”

a. h b. “hlm”

c. lm d. hlm

3. What will be the output of the given code?

>>>str1 = ‘hello world’

>>>str2 = ‘computer’

>>>str1 [-2]

a. e b. ld

c. l d. er

4. Which operator is used to represent escape character?

a. \ b. \\
c. \’ d. /

5. What will be the output of the given code?

>>> string = “Hello COMPUTER!”

>>> len(string)

a. 14 b. 15

c. 13 d. 16

6. What will be the output of len([4, 5, 7, 9]).

a. 1 b. 9

c. 4 d. 3

7. What will be the output of the given code?

>>>”python!”[3:]

a. hon! b. hon

c. “hon” d. “hon!”

8. Which of the following functions checks whether all the


characters in a string are whitespaces?

a. isnumeric() b. swapcase

c. istitle() d. isspace()

9. Which operator is known as String Formatting operator in


Python?

a. \\ b. \

c. % d. **

10. Which one of the following functions replaces all


occurrences of old substring in string with new string?

a. replace(new, old[,max]) b. replace(old,


new[,max])
c. replace(old, new[max]) d. replace(new,
old[max])

11. If we do not give any value for the index before the colon,
which element of the string will the slice start from?

a. First b. Zero

c. Second d. Last

12. If we do not give any value for the index after the colon,
which element of the string will the slice go up to?

a. Third b. First

c. Fourth d. Last

13. If the second index is smaller than the first index, what will
be the output?

a. String itself b. Null

c. Empty string d. First Character

14. What will be the output of the given code?

>>>str = “*”

>>>seq = (“hello”,”world”)

>>>print ([Link](seq))

a. “hello”*”world” b. hello*world

c. hello world d. error

15. What will be the output of the given code?

>>>str = “John is good student”

>>>print ([Link](‘ ‘,2))

a. [‘John’, ’is’, ’good student’]

b. [‘John’, ’is’, ’good’, ‘student’]

c. [‘John is’, ’good student’]


d. [‘John is’, ’good’, ‘student’]

16. What will be the output of the given code?

>>>print(‘wxyZ!56’.swapcase())

a. WXYZ! b. WXYz56@

c. Wxyz d. WXYz!56

17. What will be the output of the given code?

>>>print (‘john’ boy, good’ .title())

a. John boy good b. John Boy good

c. John Boy Good d. none

18. Which of the following will separate all the items in list?

a. * b. ,

c. ; d. &

19. What is the repetition operator in lists?

a. * b. ,

c. ; d. &

20. Which of the following functions will sort a list?

a. [Link] b. [Link]([func])

c. [Link][func] d. [Link](func)

21. What will be the output of the given code?

list = [‘john’, ‘book’, 123, 3.45, 105, ‘good’]

>>>print (list[4:])

a. [3.45, 105, ‘good’] b. [‘john’, ‘book’, 123,


3.45]

c. [105, ‘good’] d. [123, 3.45]

22. What will be the output of the given code?


list = [‘john’, ‘book’, 123, 3.45, 105, ‘good’]

>>>print (list[2:5])

a. [123, 3.45, 105] b. [‘book’, 123, 3.45, 105,


‘good’]

c. [‘john’, ‘book’, ‘good’] d. [123, 3.45, 105, ‘good’]

23. Which of the following functions will give the total length
of a list?

a. Len b. len(list)

c. max(len) d. max len(list)

24. What will be the output of the given code?

list = [2356, 325.8, 3450, 1897]

>>>print(“minimum value in:”, list, “is”, min(list))

a. 3450 b. 1897

c. 2356 d. 325.8

25. What will be the output of the given code?

list(“hi”)

a. [‘hi’] b. [“hi” ]

c. [‘h’, ‘i’] d. hi

26. Which of the following functions will be used to shuffle a


list?

a. [Link](list) b. [Link]()

c. shuffle(list) d. [Link]()

27. What will be the output of the given code?

list=[1, 2, 3, 4, 10]

>>>print (list[-1])
a. 1 b. 10

c. 4 d. Error

28. What will be the output of the given code?

list=[1, 2, 3, 4, 10]

>>>print (list[:-1])

a. [4, 3, 2, 1] b. 10

c. [1, 2, 3, 4] d. error

29. Which of the following functions will be used to add a new


element to a list?

a. [Link](obj) b. [Link](obj)

c. [Link]() d. [Link]()

30. Which of the following functions will be used to insert 8 to


the forth position in the list?

a. [Link](8, 4) b. [Link](4, 8)

c. [Link](8, 4) d. [Link](4, 8)

31. What will be the output of the given code?

list=[1, 2, 3, 4, 10]

>>>del list[3]

>>>print(list)

a. [1, 2, 4, 10] b. [1, 2, 3, 10]

c. [1, 2, 4] d. error

32. Which of the following functions is used to remove string


“python” from the list?

a. [Link](python) b. [Link](“python”)

c. [Link](“python”) d. [Link]
33. Which of the following functions is used to return a tuple
to a list?

a. list(seq) b. seq(list)

c. list(tuple) d. tuple(list)

Answers to Multiple Choice Questions

1. b 2. d 3. c 4. a 5. b 6. c 7. a 8. d 9. c 10. b

11. a 12. d 13. c 14. b 15. a 16. d 17. c 18. b 19. a 20. b

21. c 22. a 23. b 24. d 25. c 26. a 27. b 28. c 29. a 30. d

31. b 32. c 33. A

1. What is a tuple and how is it created in Python?

Ans. In Python programming, tuples are just like the lists we


have seen in earlier chapters. Tuples are the sequence or
series of different types of values separated by commas.
Creating tuples is pretty easy in Python. In order to create a
tuple, all the items or elements are placed inside parentheses
separated by commas and assigned to a variable. Tuples can
have any number of different data items (i.e., integer, float,
string, list, etc.).

2. How are the values in a tuple accessed?

Ans. In order to access the values in a tuple, we need to use


the index number enclosed in square brackets along with the
name of the tuple.

Example

>>>tuple = (10,20,30,40)

>>>tuple[1]

20 # Output

>>>tuple[3]
40 # Output

3. What are concatenation and iteration? Give one example of


concatenation.

Ans. Concatenation:

The concatenation operator works in tuples in the same way as


in lists. This operator concatenates two tuples. Concatenation
is done by the + operator in Python.

Example

>>>t1 = (10,20,30)

>>>t2 = (50,60)

>>>t3 = t1 + t2

>>>print t3

(10, 20, 30, 50, 60) # Output

Iteration:

Iteration is done in tuples using for loop. It helps in traversing


the tuple.

4. Give one-one example for zip, max and min methods.

Ans. >>>tuple1 = (‘a’,’b’,’c’)

>>>tuple2 = (1,2,3)

>>>max(tuple2)

3 # Output

>>>min(tuple1)

‘a’ # Output

>>>zip(tuple1,tuple2)

[(‘a’, 1), (‘b’, 2), (‘c’, 3)] # Output


5. What is a Dictionary in Python?

Ans. Python dictionary is an unordered collection of items or


elements. All other compound data types in Python have only
values as their elements or items whereas the dictionary has a
key: value pair, i.e., each value is associated with a key. In the
list and the tuple, there are indices that are only of integer
type, but in the dictionary, we can have keys of any type.

6. Give one example of accessing the value in dictionary.

Ans. >>> dict1 = {1:’a’,2:’b’,3:’c’}

>>> dict1[1]

‘a’ # Output

>>> dict1[2]

‘b’ # Output

>>> dict1[3]

‘c’ # Output

7. What are the different methods used in deleting elements


from dictionary?

Ans. pop()method removes that item from the dictionary for


which the key is provided. It also returns the value of the item.

popitem()method is used to remove or delete and return an


arbitrary item from the dictionary.

clear() method removes all the items or elements from a


dictionary at the same time.

Python also provides a del keyword that deletes the dictionary


itself.

8. What are the two properties of key in the dictionary?


Ans. 1. One key in a dictionary cannot have two values, i.e.,
duplicate keys are not allowed in the dictionary; they must be
unique.

2. Keys are immutable, i.e., we can use string, integers or


tuples for dictionary keys, but cannot use something like
[‘key’].

Multiple Choice Questions

1. Which of the following sequence data type is similar to the


tuple?

a. Dictionaries b. List

c. String d. function

2. In which operator are tuples enclosed?

a. { } b. [ ]

c. <> d. ( )

3. Which of the following is a Python tuple?

a. [7, 8, 9] b. {7, 8, 9}

c. (7, 8, 9) d. <7, 8, 9>

4. What will be the output of the following code?

>>>tuple = (‘john’, 100, 345, 1.67, ‘book’)

>>>print(tuple[0])

a. John b. 0

c. Book d. error

5. What will be the output of the following code?

>>>tuple = (‘john’, 100, 345, 1.67, ‘book’)

>>>print(tuple[2:4])
a. (345, 1.67, ‘book’) b. (100, 345, 1.67)

c. (345, 1.67) d. (100, 345)

6. Which of the following will not be correct if tuple = (10, 12,


14, 16, 18)?

a. print(min(tuple)) b. print(max(tuple))

c. tuple[4] = 20 d. print(len(tuple))

7. What will be the output of the following code?

>>>tuple = (‘john’, 100, 345, 1.67, ‘book’)

>>>print(tuple[3:])

a. (1.67, ‘book’) b. (345, 1.67)

c. (‘john’, 100, 345) d. (345, 1.67, ‘book’)

8. What will be the output of the following code?

>>>tuple = (1, 5, 8, 9)

>>>print(tuple[1:-1])

a. (1, 5, 8) b. (1, 5)

c. (5, 8, 9) d. (5, 8)

9. Which of the following statements is used to delete an entire


tuple?

a. Remove b. exit

c. del d. backspace

10. What will be the output of the following code?

>>>tuple1 = (3, 5, 7, 9)

>>>tuple2 = (3, 5, 9, 7)

>>>tuple1 < tuple2

a. Error b. False
c. True d. Null

11. Which of the following functions in Python is used to


convert a string into a tuple?

a. tuple(str) b. str(tuple)

c. repr(tuple) d. list(tuple)

12. Which of the following data types does not belong to


Python?

a. String b. Tuple

c. Dictionary d. Structure

13. Which of the following functions will return a list into a


tuple?

a. tuple(list) b. len(tuple)

c. tuple(seq) d. append(tuple)

14. Which core data type in Python is an unordered collection


of key-value pairs?

a. Tuple b. dictionary

c. function d. list

15. In which of the following operators are dictionaries


enclosed?

a. { } b. ( )

c. [ ] d. <>

16. Which of the following represent keys in the dictionary?

a. function or list b. numbers or list

c. strings or functions d. numbers or strings

17. Which operator is used to access the values in dictionary?

a. { } b. ( )
c. [ ] d. <>

18. Which of the following statements will not create a


dictionary?

a. {245:”book”, 1234:code} b. (“book”:245,


“code”:1234)

c. { } d. {“book”:245,
“code”:1234}

19. Which of the following forms do dictionaries appear in?

a. keys and values b. only keys

c. list and keys d. only values

20. What are the keys in the following code?

dictionary = {“book”:245, “code”:1234}

a. 245 and 1234 b. “book” and “code”

c. “book”, 245, “code” and 1234 d. (“book”:245,


“code”:1234)

21. Which of the following methods is used to remove entire


elements of a dictionary?

a. remove() b. remove{}

c. clear() d. clear{}

22. What will be the output of the following code?

dict = {‘name’: ‘ravi’, ‘age’:35}

“ravi” in dict

a. True b. false

c. error d. none

23. Which of the following functions of the dictionary gets all


the keys from the dictionary?
a. [Link]() b. [Link]()

c. allkeys() d. getkeys()

24. What will be the output of the following code?

dict = {‘name’,‘ravi’,‘age’:35}

>>>print dic[‘age’]

a. Age b. 35

c. Ravi d. error

25. What will be the output of the following code?

dict = {‘name’:’ravi’, ‘age’:35}

>>>print dict[‘age’]

a. Age b. [age]

c. 35 d. error

26. Which of the following functions will be used to get the


number of entries in dictionary?

a. len(dict) b. [Link]

c. size(dict) d. [Link]

27. What will be the output of the following code?

dict1 = {’john’:25,’Salary’:18,000}

dict2 = {’kathy’:35,’Salary’:28,000}

>>>print dict1 > dict2

a. True b. error

c. false d. none

28. What will be the output of the following code?

dict = {’john’:25,’Salary’:18,000,‘Age’:45}

>>>print (len(dict))
a. 6 b. 5

c. 3 d. none

29. Which of the following functions of the dictionary gets all


the values from the dictionary?

a. [Link]() b. [Link]()

c. getvalues() d. getvalue()

30. Which of the following functions returns a list of the


dictionary?

a. [Link]() b. [Link]()

c. [Link]() d. [Link]()

31. What value is returned by the method dict.has_key(key),


when the key is in the dictionary?

a. False b. True

c. Error d. None

Answers to Multiple Choice Questions

1. b 2. d 3. c 4. a 5. b 6. c 7. a 8. d 9. c 10. b

11. a 12. d 13. c 14. b 15. a 16. d 17. c 18. b 19. a 20. b

21. c 22. a 23. b 24. d 25. c 26. a 27. b 28. c 29. a 30. d

31. b

1. What are text files? How are they useful?

Ans. A file in a computer is a location for storing some related


data. It has a specific name. The files are used to store data
permanently on to a non-volatile memory (such as hard disks).
As we know, the Random Access Memory (RAM) is a volatile
memory type because the data in it is

lost when we turn off the computer. Hence, we use files for
storing of useful information or data for future reference.

2. What is the syntax for opening a file in Python?

Ans. Syntax

file object = open(file_name [, access_mode])

■ file_name: File name contains a string type value containing


the name of the file which

we want to access.

■ access_mode: The value of access_mode specifies that in


which mode we want to open

the file, that is, read, write, append, etc. The default
access_mode is r(read only).

3. What is the syntax for closing a file? Give one example.

Ans. Syntax

[Link]()

Example

# open a file

>>> f = open(“[Link]”,”r”)

# perform reading operation

>>>[Link]() # close the file

4. Give the syntax for reading from a file. What is the work of
the readline() function?

Ans. Syntax
[Link]([size])

The count parameter size gives the number of bytes to be read


from an opened file. It starts reading from the beginning of the
file until the size given. If no size is provided, it ends up
reading until the end of the file.

5. What are the various file positions methods?

Ans. In Python, the tell() method tells us about the current


position of the pointer. The current position tells us where
reading will start from at present.

We can also change the position of the pointer with the help of
the seek() method. We pass the number of bytes to be moved
by the pointer as arguments to the seek() method.

6. How are renaming and deleting performed on a file? Give


the syntax for each.

Ans. Renaming a file

Renaming a file in Python is done with the help of the rename()


method. The rename() method is passed with two arguments,
the current filename and the new filename.

Syntax

[Link](current_filename, new_filename)

Deleting a File

Deleting a file in Python is done with the help of the remove()


method. The remove() method takes the filename as an
argument to be deleted.

Syntax

[Link](filename)

Multiple Choice Questions


1. Which of the following functions is used to open a file in
Python?

a. open{} b. open()

c. open[] d. Open()

2. What is a file object also known as?

a. Object source b. File

c. Object file d. Handle

3. Which of the following is the default mode while opening a


file?

a. Binary b. Number

c. Text d. None

4. What are the two modes that are used to open a file?

a. Text or Binary b. Number or Text

c. Number or Binary d. Text or Number

5. Which of the following is incorrect when we use the binary


mode?

a. Image Files b. Text Files

c. exe Files d. Non-Text Files

6. What is the default file access mode?

a. write (w) b. append

c. read (r) d. None

7. What is the syntax for opening a file in current directory?

a. f = open(“[Link]”,’r’) b. f = open(“[Link],’w’)

c. f = open(“[Link],’a’) d. f = open(“[Link]”)

8. What will be used to open a file C:/[Link] for reading?


a. f = open(“C:/[Link]”) b. f = open(“C:\[Link]”,’r’)

c. f = open(“C://[Link]”,’r’) d. f = open(“C:/[Link]”,’r’)

9. Which of the following statements is correct while using r+


mode for opening a file?

a. Opens a file for reading only

b. Opens a file for reading in binary format

c. Opens a file for both reading and writing

d. Opens a file for writing only

10. At what position will the file pointer be placed whenever


we open a file for reading or writing?

a. Middle b. Beginning

c. Second line d. End

11. Which of the following statements is not correct?

a. When a file is opened for reading, if the file does not exist,
an empty file will be opened.

b. When a file is opened for writing, overwrites the file if the


file exists.

c. When a file is opened for writing, if the file does not exist,
creates a new file for writing.

d. When a file is opened for reading, if the file does not exist,
an error occurs.

12. Whenever we open a file for appending, at what position


will the file pointer be placed?

a. Middle b. Beginning

c. Second line d. End

13. Which of the following statements is correct while using


‘a+’ mode for opening a file?
a. Opens a file for appending only

b. Opens a file for writing only

c. Opens a file for both appending and reading

d. Opens a file for both appending and writing

14. Which of the following statements is correct while using ‘x’


mode?

a. Open a file for reading b. Open a file for exclusive


creation

c. Open a file for appending d. Does not open a file

15. In disk, the files are stored in?

a. Bytes b. Bit

c. Kilobits d. Gigabytes

16. What is the syntax to close a file?

a. [Link]() b. close()

c. close(); d. [Link]()

17. The write() method does not add a newline character (‘\n’)
at which position of the string?

a. Beginning b. Middle

c. End d. None of the above

18. What is the syntax of the write() method?

a. [Link]() b. [Link](string)

c. [Link]() d. [Link]()

19. What is the syntax for reading from a file?

a. [Link]([size]) b. [Link](size)

c. [Link]() d. [Link](size)
20. Which module does Python provide to perform operations
like renaming and deleting files?

a. Is b. os

c. op d. ip

21. Which of the following methods is used to create


directories in the current directory?

a. chdir() b. rmdir()

c. mkdir() d. mcdir()

22. Which of the following methods is used to change the


current directory?

a. chdir() b. rmdir()

c. mkdir() d. mcdir()

23. Which of the following methods is used to display the


current working directory?

a. mkcwd( ) b. getcwd()

c. chcwd() d. setcwd()

24. Which of the following methods is used to delete the


directory?

a. chdir() b. mkdir()

c. mrdir() d. rmdir()

25. Which of the following is not an attribute of a file in


Python?

a. Mode b. Name

c. Delete d. Closed

26. Which of the following is a condition that is caused by a


runtime error in the program?

a. Exception b. Assertion
c. Attribute d. Error

27. How many except statements can a try-except block have?

a. One b. More than zero

c. Zero d. None

28. Which keyword is used to prepare a block of code that


throws an exception?

a. except b. import

c. try d. None

29. Which of the following is defined to catch the exception


thrown by the try block?

a. except b. import

c. index d. None

30. Which block will the statements be executed in after the


try block if no exception is raised inside a try

block?

a. Try b. Except

c. Finally d. else

31. Check whether the following code is correct or not.

try:

# Do something

except:

# Do something

finally:

#Do something

a. Yes
b. No, finally cannot be used with except

c. No, finally can be used after try block

d. None of the above

32. Check whether the following code is correct or not?

try:

# Do something

except:

# Do something

else:

#Do something

a. Yes

b. No, else cannot be used with except

c. No, else can be used after try block

d. None of the above

Answers to Multiple Choice Questions

1. b 2. d 3. c 4. a 5. b 6. c 7. a 8. d 9. c 10. b

11. a 12. d 13. c 14. b 15. a 16. d 17. c 18. b 19. a 20. b

21. c 22. a 23. b 24. d 25. c 26. a 27. b 28. c 29. a 30. d

31. b 32. a

Common questions

Powered by AI

Sequences such as lists, tuples, and strings use numerical indices to access their items, whereas dictionaries use keys, which can be of any immutable type. Dictionaries are unordered, mapping keys to values for direct access, unlike sequences that have ordered elements .

The list.remove() method removes the first occurrence of a specified item, such as list.remove("python"), whereas the pop() method removes an item by its index and can return the removed item. The pop method requires an index, making it different from remove .

In Python, the concatenate operator '+' combines lists and strings into a single new list or string, while the 'in' operator checks for the presence of an element within a list or a substring within a string .

Python lists are mutable, meaning the values within a list can be changed after the list's creation. For example, given a list [1,2,3,4], changing the third element using list[2] = 6 modifies the list to [1,2,6,4].

The len function in Python calculates the number of characters in a string, effectively returning the length of the string. For example, when used with the string 'My name is Anil', len returns 15 .

Files in Python are manipulated using various methods. The open function, for instance, opens a file in a specified mode ('r' for read). Renaming a file involves using os.rename(current_filename, new_filename), while deleting a file uses os.remove(filename).

Exceptions in Python are managed using try-except blocks, where the try block contains the code that might cause an exception, and the except block handles it. A finally block can be used to execute code irrespective of whether an exception occurs, ensuring cleanup actions .

The file pointer position dictates where file reading or writing starts. Python uses the tell() method to report the current pointer position and the seek() method to move the pointer to a desired position. These control the start point for subsequent file operations .

Tuples in Python, unlike lists, are immutable sequences of values, meaning their contents cannot be changed once created. A tuple can be created by placing elements inside parentheses, separated by commas, such as tuple = (10,20,30).

In Python, dictionary keys must be immutable, which ensures that the key remains consistent through the program execution. Thus, strings, integers, or tuples can be used as keys, but mutable types like lists cannot. For instance, a tuple can serve as a dictionary key .

You might also like