MCQ for Python Users
MCQ for Python Users
MCQ for Python Users
for
Python Users
Get ready for computer science
examinations
with 5000+ Python MCQ
ISBN: 978-93-55517-739
All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any
form or by any means or stored in a database or retrieval system, without the prior written permission
of the publisher with the exception to the program listings which may be entered, stored and executed
in a computer system, but they can not be reproduced by the means of publication, photocopy,
recording, or by any electronic and mechanical means.
All trademarks referred to in the book are acknowledged as properties of their respective owners but
BPB Publications cannot guarantee the accuracy of this information.
www.bpbonline.com
Dedicated to
This book culminates a few years of intense learning and research experience.
We have been fortunate to interact with many people who have influenced us
greatly. One of the pleasures of finally finishing is this opportunity to thank
them. We would like to place on record and acknowledge the works of all
those great authors whose work we have referred to in preparing this book.
A few people want to thank you for the continued and ongoing support they
have given us while writing this book. First and foremost, we would like to
thank our family members for continuously encouraging us to write the book
— we could have never completed this book without their support.
We are also grateful to BPB Publications for their guidance and expertise in
bringing this book to fruition. Revising this book was a long journey, with
valuable participation and collaboration of reviewers, technical experts, and
editors.
We would also like to acknowledge the valuable contributions of our
colleagues and co-workers during many years working in academics, who
have taught us so much and provided valuable feedback on this work.
Finally, we would like to thank all the readers who have taken an interest in
our book and for their support in making it a reality. Your encouragement has
been invaluable.
Preface
Bringing the book “MCQ for Python Users” gives us immense pleasure.
Python is the most popular programming language and is widely used among
programmers. The book is intended for the students of various courses who
can use this high-level programming language as an effective tool for
Problem-solving. Python is used to develop applications of any stream and is
not restricted only to computer science. This book contains more than 5000
MCQ questions and answer keys.
These questions and answers serve as a means to assess your proficiency in
Python programming. If you possess prior knowledge of Python, you can
utilize it to ascertain the number of queries you can independently try without
assistance. Before your job interview, it would be advisable to review these
questions. For teachers or tutors instructing Python, these multiple-choice
questions (MCQ) serve as a valuable assessment tool to gauge the extent to
which pupils have grasped the material given. The intended difficulty level of
the questions is aimed at those who are at the Beginner Level in Python,
either those who are just beginning to study Python or those who have
recently acquired knowledge in Python. The book also provides answers to
all the questions.
This book is for everyone from an engineering and science background. It is
also for B.Tech. B.E., BCA, BSc, M.Tech, PGDCA, M.E., MCA, M.Com.,
MSc, Ph.D., other UG graduates, and PG graduates. With this book, you will
gain the knowledge and skills in Python. We hope you will find this book
informative and helpful.
The book is divided into 20 chapters covering MCQs of all aspects of
Problem-Solving with Python with a touch of Machine Learning. The details
are listed below.
Chapter 1: Fundamentals of Programming – This chapter contains MCQ
related to the basics of programming, including language translators,
instructions, and various types of statements.
Chapter 2: Introduction to Python – It presents MCQ for Python basics,
installation, program writing, and executions.
Chapter 3: Data type, Operators, and Expressions – It covers various
MCQs related to Python data types, operators, and different expressions.
Chapter 4: Control Flow Statements – MCQs related to conditional and
looping statements.
Chapter 5: Functions - This chapter covers various MCQs related to
functions that can be used in Python.
Chapter 6: Sequence-String – This chapter focuses on MCQs targeting
Python’s sequence manipulation, emphasizing string handling.
Chapter 7: Lists – This chapter includes various List related MCQs.
Chapter 8: Tuples – This chapter includes various MCQs for Tuples.
Chapter 9: Dictionaries – This chapter covers MCQs for dictionary data
structure and various operations applied to the dictionary.
Chapter 10: File Handling – Python provides a built-in feature to build,
write, and read files. This chapter includes MCQs related to various
operations that are used on files.
Chapter 11: Exception Handling – This chapter highlights MCQs related to
the exception-handling functionality of Python.
Chapter 12: Modules – It includes Python module-related MCQs.
Chapter 13: Packages – It includes MCQs related to Python packages.
Chapter 14: Object-oriented Programming – This chapter covers MCQs
related to Python’s object-oriented programming.
Chapter 15: Graphical User Interfaces in Python – This chapter contains
MCQs for Pythons GUI programming. Questions are related to tkinter,
widgets, frames, and application designing.
Chapter 16: Machine Learning with Python – covers MCQs related to
various machine learning concepts.
Chapter 17: Clustering with Python – This chapter’s MCQ explores the
concept and methodologies of clustering algorithms using the Python
programming language.
Chapter 18: Applications of Python – It includes MCQs related to various
Python applications. Questions include data analysis, machine learning, web
development, automation, and more.
Chapter 19: Python Error Finding MCQ – The collection of MCQs
focused on identifying and resolving errors in Python code.
Chapter 20: Database Programming with Python – It includes various
MCQs related to database handling through Python programming.
Errata
We take immense pride in our work at BPB Publications and follow best
practices to ensure the accuracy of our content to provide with an indulging
reading experience to our subscribers. Our readers are our mirrors, and we
use their inputs to reflect and improve upon human errors, if any, that may
have occurred during the publishing processes involved. To let us maintain
the quality and help us reach out to any readers who might be having
difficulties due to any unforeseen errors, please write to us at :
[email protected]
Your support, suggestions and feedbacks are highly appreciated by the BPB
Publications’ Family.
Did you know that BPB offers eBook versions of every book published, with PDF and ePub files
available? You can upgrade to the eBook version at www.bpbonline.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in touch with us at :
[email protected] for more details.
At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks.
Piracy
If you come across any illegal copies of our works in any form on the internet, we would be
grateful if you would provide us with the location address or website name. Please contact us at
[email protected] with a link to the material.
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on the site
that you purchased it from? Potential readers can then see and use your unbiased opinion to make
purchase decisions. We at BPB can understand what you think about our products, and our authors
can see your feedback on their book. Thank you!
For more information about BPB, please visit www.bpbonline.com.
1. Fundamentals of Programming
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
2. Introduction to Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
5. Functions
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
6. Sequence-String
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
7. Lists
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
8. Tuples
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
9. Dictionaries
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
12. Modules
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
13. Packages
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
Introduction
Programming serves as the fundamental pillar of our progressively
computerized society. The software that operates our computers, mobile
devices, and the other interconnected networks that constitute our
contemporary existence is fueled by this force. Acquiring proficiency in the
art and science of programming empowers individuals with a formidable
instrument for problem-solving, work automation, and the realization of
creative concepts. This chapter starts the process of developing Multiple-
Choice Questions (MCQs) that center around the core principles of
programming. The MCQs provided here are intended to be a beneficial tool
for individuals seeking to enhance their knowledge, instructors aiming to
facilitate learning, and those with an interest in comprehending the
fundamental principles that form the basis of programming. The importance
of these MCQs resides in their capacity to evaluate, strengthen, and enhance
an individual’s understanding of programming concepts. Whether one is an
inexperienced individual on their programming journey or an experienced
developer aiming to review fundamental concepts, the following inquiries
offer a systematic approach for self-evaluation and knowledge acquisition.
Objectives
The objective of this chapter, titled Fundamentals of Programming MCQs, is
to enhance the knowledge and skills of learners and instructors in the
programming field. It aims to offer a systematic and interactive approach to
comprehending the fundamental ideas that underpin the realm of coding and
software development.
14. What does the term syntax error refer to, in programming?
a. A logical error in the code
b. A mistake in the program’s output
c. An error in the program’s design
d. A violation of the programming language’s rules
16. What does the acronym IDE stand for in the context of
programming?
a. Integrated Design Environment
b. Integrated Development Environment
c. Interconnected Development Environment
d. Interactive Developer Environment
22. What is the term for a named storage location in memory that
holds a value?
a. Function
b. Variable
c. Operator
d. Constant
28. What is the term for a value that does not change during the
execution of a program?
a. Constant
b. Variable
c. Parameter
d. Function
39. What is the term for a variable that is accessible from any part of
a program?
a. Global variable
b. Local variable
c. Constant variable
d. Instance variable
61. What does the acronym SQL stand for in database programming?
a. Structured Query Language
b. Sequential Query Language
c. Simple Query Logic
d. System Query Language
164. What is the primary goal of the Systems Development Life Cycle
(SDLC)?
a. To complete a project as quickly as possible
b. To ensure that software projects are always error-free
c. To provide a structured approach to software development
d. To eliminate the need for project documentation
165. Which phase of the SDLC involves gathering and analyzing user
requirements?
a. Design phase
b. Development phase
c. Testing phase
d. Requirements phase
166. In the SDLC, what is the primary purpose of the design phase?
a. To write code and develop the software
b. To define the scope of the project
c. To create detailed specifications for the software’s architecture
and components
d. To perform testing and validation
168. In the SDLC, what is the primary objective of the testing phase?
a. To write code and develop the software
b. To ensure that the software meets user requirements and
functions correctly
c. To gather and analyze user requirements
d. To create design specifications
176. Which SDLC model is known for its iterative and risk-driven
approach to development?
a. Waterfall model c. Spiral model
b. Agile model d. V-Model
177. What is the primary focus of the scoping phase in the SDLC?
a. To design the system architecture
b. To gather and analyze user requirements
c. To develop the software
d. To create user documentation
178. What is the main objective of the prototyping phase in the SDLC?
a. To gather and analyze user requirements
b. To design the system architecture
c. To create a working model of the software for user feedback
d. To perform testing and validation
241. Higher-order functions are not built into which of the following:
a. Structural language
b. Object-oriented programming
c. JAVA
d. C++
242. Animations and interactivity with the user on web pages can be
done by:
a. PHP
b. Java script
c. Visual Basic
d. Visual C#
243. Java Script was first released in:
a. 1975 c. 1987
b. 1980 d. 1995
244. Procedural language contains a systematic order of:
a. Statements
b. Objects
c. Classes
d. Operations
245. Data type is shifted from short type to long type when:
a. Value range decreases
b. Value range increases
c. Value range becomes zero
d. Value range becomes infinite
Conclusion
In a swiftly progressing technical environment, these MCQs provide a solid
basis to those seeking to become programmers and serve as a beneficial
review for experienced developers. The authors highlight the enduring
significance of programming basics, which retain their core character
irrespective of changes in programming languages and paradigms. The
purpose of providing this MCQ is to enhance the abilities of persons in the
domains of coding and problem-solving, therefore enabling them to achieve
exceptional performance.
These MCQs facilitate a more profound comprehension of the fundamental
programming concepts, both as an initial stage for individuals starting their
programming expedition and as a dependable resource for those already
engaged in the discipline. By engaging in this practice, we actively contribute
to the development of a worldwide community consisting of skilled and
inventive programmers.
In the subsequent chapter, an examination of MCQs about the introductory
aspects of the Python programming language will be undertaken.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
In this chapter, we will provide MCQs for introduction to Python, a powerful
and versatile programming language that has gained tremendous popularity
among developers around the globe. Python is known for its simplicity and
readability, making it an ideal choice for beginners and professionals. These
MCQs will be a foundation for your Python journey. We will start by
exploring the fundamentals of Python syntax, data types, control flow, and
functions.
Objectives
The primary aim of developing MCQs is to provide a comprehensive
understanding of the Python programming language, enabling readers to gain
knowledge of its features, syntax, and basic data manipulation operations.
This chapter aims to introduce Python as a versatile programming language
for beginners, highlighting its ease of use, extensive library support, and
applicability to various domains such as data science, web development, and
automation.
52. Which of the following is a Python data structure that can be used
to store key-value pairs?
a. Dictionary
b. List
c. Set
d. Tuple
77. Which of the following is the correct syntax for a for loop in
Python?
a. for i in range(10):
b. for i in range(10): print(i)
c. for i in range(10): i += 1
d. All of the above
79. What is the difference between the break and continue statements
in Python?
a. The break statement terminates the loop, while the continue
statement skips the current iteration of the loop.
b. The break statement skips the current iteration of the loop, while
the continue statement terminates the loop.
c. Both statements terminate the loop.
d. Both statements skip the current iteration of the loop.
87. Which of the following is a valid use case for a nested if statement?
a. To check if a number is even or odd and prime or not.
b. To check if a student is eligible for admission to a college based
on their grades and test scores.
c. To check if a user is logged in to a website and has the necessary
permissions to access a particular page.
d. All of the above
88. Which of the following is a good practice when writing code with
control statements?
a. Use comments to explain what your code is doing.
b. Indent your code properly to make it more readable.
c. Avoid using nested if statements whenever possible.
d. All of the above
103. What is the output of the following code:True and False == False
a. True
b. False
c. TypeError
d. None of the above
114. How do you find out what functions and variables are defined in a
module?
a. Use the help() function
b. Use the dir() function
c. Use the inspect() module
d. All of the above
a. import my_module
b. include my_module
c. require my_module
d. All of the above
120. Which of the following is a valid way to import all of the functions
and variables from a module called my_module?
a. import my_module
b. from my_module import *
c. include my_module
d. require my_module
123. Which of the following is a valid way to remove a module from the
global namespace?
a. del sys.modules[“my_module”]
b. delete my_module
c. my_module.remove()
d. None of the above
126. Which of the following is a valid way to set the global namespace
for a module?
a. __name__ = ‘__main__’:
b. sys.modules[‘my_module’] = {}
c. del sys.modules[‘my_module’]
d. None of the above
127. Which of the following is a valid way to get the path to a module
file?
a. os.path.dirname(__file__)
b. os.path.basename(__file__)
c. os.path.abspath(__file__)
d. All of the above
128. Which of the following is a valid way to get the list of all modules
imported by the program?
a. sys.modules
b. sys.path
c. sys.argv
d. None of the above
136. How do you access a private function from outside the module?
a. Use the dot notation, for example my_module._add__(x, y)
b. Use the getattr() function, for example getattr(my_module,
‘_add__’)(x, y)
c. You cannot access a private function from outside the module.
d. None of the above.
159. What is the difference between the import statement and the from
statement?
a. The import statement imports the entire library, while the from
statement imports specific functions or classes from the library.
b. The import statement is faster than the from statement.
c. The import statement is more readable than the from statement.
d. None of the above
164. What are some of the best resources for learning more about
Python libraries?
a. The Python documentation
b. The Python subreddit
c. Stack Overflow
d. All of the above
165. What is a good way to test your code when using libraries?
a. Write unit tests for your code.
b. Use a code coverage tool to measure the coverage of your unit
tests.
c. Both of the above.
d. None of the above.
167. What is the difference between a number data type and a string
data type?
a. Number data types can only store numbers, while string data
types can store any sequence of characters.
b. Number data types are faster than string data types.
c. Number data types are more flexible than string data types.
d. None of the above
168. What is the difference between a list data type and a tuple data
type?
a. Lists are mutable, while tuples are immutable.
b. Lists can store any type of data, while tuples can only store
elements of the same type.
c. Lists are faster than tuples.
d. All of the above.
169. What is the difference between a dictionary data type and a set
data type?
a. Dictionaries are mutable, while sets are immutable.
b. Dictionaries store key-value pairs, while sets store unique
elements.
c. Dictionaries are faster than sets.
d. All of the above.
170. What is the best way to check the data type of a variable in
Python?
a. Use the type() function.
b. Use the isinstance() function.
c. Both (a) and (b).
d. None of the above
178. What is the difference between a primitive data type and a non-
primitive data type?
a. Primitive data types are built-in data types, while non-primitive
data types are user-defined data types.
b. Primitive data types are immutable, while non-primitive data
types are mutable.
c. Primitive data types are faster than non-primitive data types.
d. All of the above
193. What is the best way to find the union of two sets?
a. Use the | operator.
b. Use the union() method.
c. Both (a) and (b).
d. None of the above
194. What is the best way to find the intersection of two sets?
a. Use the & operator.
b. Use the intersection() method.
c. Both (a) and (b).
d. None of the above
195. What is the best way to find the difference of two sets?
a. Use the - operator
b. Use the difference() method
c. Both (a) and (b)
d. None of the above
196. What is the best way to create a new set from a subset of another
set?
a. Use the set() function
b. Use the slice() operator
c. Both (a) and (b)
d. None of the above
199. What is the best way to check if two sets are equal?
a. Use the == operator
b. Use the is operator
c. Both (a) and (b)
d. None of the above
204. What is the best way to check the data type of a variable in
Python?
a. Use the type() function.
b. Use the isinstance() function.
c. Both (a) and (b).
d. None of the above.
205. Which of the following is a valid Python data type?
a. Boolean c. float
b. integer d. All of the above.
206. What is the difference between a literal and a variable?
a. A literal is a value that is written directly into the code, while a
variable is a named reference to a value.
b. Literals are faster than variables.
c. Literals are more flexible than variables.
d. None of the above
212. What is the best way to optimize your code for performance?
a. Use profiling tools to identify bottlenecks in your code.
b. Choose the right data types for your needs.
c. Avoid using unnecessary loops and functions.
d. All of the above.
213. What is the difference between a shallow copy and a deep copy of
a list in Python?
a. A shallow copy creates a new list that contains references to the
same objects as the original list, while a deep copy creates a new
list that contains copies of the objects in the original list.
b. Shallow copies are faster than deep copies.
c. Deep copies are more flexible than shallow copies.
d. None of the above
233. What is the best way to find the minimum value in a list?
a. Use the max() function
b. Use the min() function
c. Both (a) and (b)
d. None of the above
237. What is the best way to extend a list with another list?
a. Use the extend() method
b. Use the += operator
c. Both (a) and (b)
d. None of the above
238. What is the best way to create a new list from a subset of another
list?
a. Use the list() function
b. Use the slice() operator
c. Both (a) and (b)
d. None of the above
239. What is the best way to check if two lists are equal?
a. Use the == operator
b. Use the is operator
c. Both (a) and (b)
d. None of the above
240. What is the best way to check if two lists are the same object?
a. Use the == operator
b. Use the is operator
c. Both (a) and (b)
d. None of the above
241. What is the best way to iterate over a list?
a. Use a for loop
b. Use a while loop
c. Both (a) and (b)
d. None of the above
242. What is the best way to find the count of a value in a list?
a. Use the count() method
b. Use the len() function
c. Both (a) and (b)
d. None of the above
249. What is the best way to add a new key-value pair to a dictionary?
a. Use the update() method
b. Use the [] operator
c. Both (a) and (b)
d. None of the above
250. What is the best way to update the value of an existing key in a
dictionary?
a. Use the update() method
b. Use the [] operator
c. Both (a) and (b)
d. None of the above
Conclusion
The questions of this chapter have provided a thorough understanding of the
basic concepts and features of the Python programming language. By MCQs
discussed in this chapter, readers are now equipped with the essentials to
continue their journey in Python programming. They will be able to write and
execute Python code, manipulate data, and solve real-world problems using
programming techniques. We hope this chapter has provided a solid
foundation and ignited your curiosity to delve deeper into Python
programming. The next chapter will comprehensively analyze MCQs
pertaining to Data type, Operators, and expressions.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
In this chapter, we will explore the MCQ of foundational concepts of Python
programming that form the building blocks of any code. Understanding data
types is crucial for effective coding as it allows us to store, manipulate, and
represent different kinds of data in our programs. Operators, however, enable
us to perform various operations on these data types, such as mathematical
calculations and logical comparisons. Expression combines data types and
operators to produce meaningful and dynamic results. This chapter will delve
into these concepts, providing practice questions to solidify your
understanding.
Objectives
By the end of this chapter, you will be able to understand the different data
types available in Python and their characteristics. You will also gain
familiarity with various operators and their usage to perform operations on
data and apply expressions effectively to manipulate data and perform
calculations. Apart from that you will also explore how to identify and use
appropriate data types, operators, and expressions to solve practical
programming problems. This will in turn help you develop a strong
foundation in Python data types, operators, and expressions, which will serve
as a basis for advanced programming concepts in Python.
42. Which of the following is a valid way to create a tuple with three
elements in Python?
a. my_tuple = 1, 2, 3
b. my_tuple = (1, 2, 3)
c. my_tuple = [1, 2, 3]
d. mytuple = {1: ‘one’, 2: ‘two’, 3: ‘three’}
49. Which of the following is a valid way to create a tuple with a single
element?
a. single_tuple = (1)
b. single_tuple = (1,)
c. single_tuple = 1,
d. single_tuple = [1]
60. What is the result of the expression True and False in Python?
a. True c. None
b. False d. Error
61. Which operator is used for logical OR in Python?
a. && c. or
b. || d. |
62. What is the result of the expression not True in Python?
a. True c. None
b. False d. Error
63. What is the result of the expression 3 == '3' in Python?
a. True c. None
b. False d. Error
64. Which operator is used for membership testing in Python?
a. in c. ==
b. is d. !=
65. What is the result of the expression 5 > 3 or 2 < 1 in
Python?
a. True c. None
b. False d. Error
66. What is the result of the expression 4 << 1 in Python?
a. 8 c. 16
b. 2 d. 1
67. Which operator is used for identity testing in Python?
a. is c. !=
b. == d. In
68. What is the result of the expression 5 + '3' in Python?
a. 8 c. 35
b. ‘53’ d. Error
69. Which of the following is the correct way to declare a variable in
Python?
a. variable x = 10 c. int x = 10
b. x = 10 d. let x = 10
70. Which operator is used for bitwise XOR in Python?
a. ^ c. |
b. & d. ~
71. Which of the following is a valid way to check if a number is even
in Python?
a. x % 2 == 0 c. iseven(x)
b. x.is_even() d. All of the above
72. What is the result of the expression 10 / 3.0 in Python?
a. 3.3333333333333335
b. 3.0
c. 3
d. 3.333
208. How many local and global variables are there in the following
Python code:
var1=5
def fn():
var1=2
var2=var1+5
var1=10
fn()
a. 1 local, 1 global variables
b. 1 local, 2 global variables
c. 2 local, 1 global variables
d. 2 local, 2 global variables
232. Which of the following is the correct extension of the Python file?
a. .python c. .py
b. .pl d. .p
233. Is Python code compiled or interpreted?
a. Python code is both compiled and interpreted
b. Python code is neither compiled nor interpreted
c. Python code is only compiled
d. Python code is only interpreted
239. Which of the following functions can help us to find the version of
Python that we are currently working on?
a. sys.version(1) c. sys.version()
b. sys.version(0) d. sys.version
240. Python supports the creation of anonymous functions at runtime,
using a construct called __________:
a. Pi
b. Anonymous
c. Lambda
d. None of the mentioned
241. What does pip stand for Python?
a. Pip Installs Python
b. Pip Installs Packages
c. Preferred Installer Program
d. All of the mentioned
Conclusion
This chapter, MCQ, comprehensively explains the fundamental concepts of
data types, operators, and expressions in Python programming. Throughout
the chapter, you have learned about the different data types available in
Python, such as numbers, strings, lists, tuples, and dictionaries. You have also
explored various operators, including arithmetic, assignment, comparison,
logical, and bitwise operators, and how they can be used to manipulate and
transform data. Additionally, you have gained knowledge about expressions
and their importance in Python programming. You have understood how to
write expressions using variables, operators, and literals to perform
calculations or evaluate conditions. In the next chapter, we will explore
control flow statements, which are essential for decision-making and
controlling the flow of execution in your programs.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Control flow statements are crucial in programming since they govern the
logical sequence and decision-making mechanisms within code. The
statements, which encompass conditionals and loops, play a crucial role in
determining the behavior of a program and are essential components in any
software development undertaking. A comprehensive grasp of control flow
statements is fundamental to proficient programming and solving complex
problems. This chapter focuses on developing MCQs about control flow
statements. The MCQs presented here have been carefully crafted to provide
a helpful educational tool for anybody seeking to enhance their understanding
of control flow in programming. This resource is intended to benefit learners,
instructors, and anyone interested in learning the complexities associated
with control flow. The use of MCQs in programming education advances the
whole field, highlighting the significance of interactive assessment tools in
improving educational achievements. These tools empower learners and
instructors since they offer a disciplined and dynamic approach to effectively
mastering the essential elements of control flow in programming.
Objectives
The primary aim of developing multiple-choice questions centered on control
flow statements is to offer a comprehensive and adaptable tool for everyone
engaged in programming education, encompassing learners and instructors.
We aim to assess learners’ understanding of fundamental programming
principles related to logic and decision-making in code by incorporating
several control flow forms, including if-else statements, loops, and switch
statements. Moreover, these MCQs allow learners to utilize their acquired
information in real-life situations, promoting the development of critical
thinking abilities and problem-solving aptitude.
86. Mala wants to make a fun program , if user enters any number a
Good or funny message will appear. She is confused that which is
the most suitable control to be used to make such program. Help
her to choose correct option:
a. If c. ifelif
b. if else d. Nested if else
87. Control flow statements in Python are used to:
a. Control the execution order of statements in a program
b. Declare variables and assign values to them
c. Perform mathematical operations
d. All of the above
103. Which of the following is NOT a valid way to exit a while loop
early?
a. break
b. return
c. raise Exception()
d. None of the above
104. Which of the following is NOT a valid way to iterate over a list?
a. fori in range(len(my_list)):
b. fori in my_list:
c. fori in enumerate(my_list):
d. fori in zip(my_list, another_list):
109. Which of the following is NOT a valid way to remove a value from
a list?
a. my_list.remove(value)
b. delmy_list[my_list.index(value)]
c. my_list.pop(my_list.index(value))
d. None of the above
110. Which of the following is NOT a valid way to create a new list
from two existing lists?
a. new_list = my_list1 + my_list2
b. new_list = list(my_list1) + list(my_list2)
c. new_list = copy.deepcopy(my_list1) + copy.deepcopy(my_list2)
d. None of the above
112. Which of the following is NOT a valid way to find the maximum
value in a list?
a. max(my_list)
b. sorted(my_list)[-1]
c. for value in my_list: if value >max_value: max_value = value
d. None of the above
113. Which of the following is NOT a valid way to find the minimum
value in a list?
a. min(my_list)
b. sorted(my_list)[0]
c. for value in my_list: if value <min_value: min_value = value
d. None of the above
117. Which of the following is NOT a valid way to add a new item to a
dictionary?
a. my_dict[key] = value
b. my_dict.update({key: value})
c. my_dict.setdefault(key, value)
d. None of the above
118. Which of the following is NOT a valid way to remove an item from
a dictionary?
a. delmy_dict[key]
b. my_dict.pop(key)
c. my_dict.popitem()
d. None of the above
120. Which of the following is the most efficient way to iterate over a
large list?
a. fori in range(len(my_list)):
b. for element in my_list:
c. fori, element in enumerate(my_list):
d. for element in my_list[::-1]:
121. Which of the following is NOT a valid way to break out of a nested
loop?
a. break c. breakinner_loop
b. breakouter_loop d. break()
122. Which of the following is NOT a valid way to continue to the next
iteration of a nested loop?
a. continue
b. continueouter_loop
c. continueinner_loop
d. continue()
123. Which of the following is NOT a valid way to exit a while loop
early?
a. break
b. return
c. raise Exception()
d. None of the above
126. Which of the following is NOT a valid way to remove a value from
a list?
a. my_list.remove(value)
b. delmy_list[my_list.index(value)]
c. my_list.pop(my_list.index(value))
d. None of the above
127. Which of the following is NOT a valid way to create a new list
from two existing lists?
a. new_list = my_list1 + my_list2
b. new_list = list(my_list1) + list(my_list2)
c. new_list = copy.deepcopy(my_list1) + copy.deepcopy(my_list2)
d. None of the above
144. Which of the following is the correct syntax for the ternary
operator:
a. x = condition ? value1 : value2
b. x = if condition : value1 else : value2
c. x = if condition : value1 : value2
d. None of the above
158. Which of the following is a valid use of the nested for loop:
fori in range(10):
for j in range(10):
print(i, j)
a. Yes b. No
159. What is the output of the following code:
fori in range(10):
for j in range(10):
ifi == j:
print(i, j)
a. 0 0
b. 1 1
c. 2 2
d. 3 3
e. 4 4
f. 5 5
g. 6 6
h. 7 7
i. 8 8
j. 9 9
k. all of the above
171. Which of the following is the correct syntax for a for loop?
for (initialization; condition; increment) {
statement;
}
a. True b. False
172. What is the purpose of a for loop?
a. To execute a statement repeatedly until a condition is met
b. To execute a statement if a condition is met
c. To execute a statement if a condition is not met
d. None of the above
173. Which of the following is the correct syntax for a while loop?
while (condition) {
statement;
}
a. True b. False
174. What is the purpose of a while loop?
a. To execute a statement repeatedly until a condition is met
b. To execute a statement if a condition is met
c. To execute a statement if a condition is not met
d. None of the above
189. What is the difference between a for loop, a while loop, and a
do-while loop?
a. A for loop is used when the number of iterations is known, a
while loop is used when the number of iterations is unknown, and
a do-while loop is used when the loop must be executed at least
once.
b. A for loop is used when the number of iterations is unknown, a
while loop is used when the number of iterations is known, and a
do-while loop is used when the loop must be executed at least
once.
c. There is no difference between a for loop, a while loop, and a do-
while loop.
d. None of the above
190. What are some common mistakes that people make when using
control flow statements?
a. Not using break statements to terminate loops or switch
statements
b. Not using continue statements to skip to the next iteration of a
loop
c. Using the wrong control flow statement for the job
d. All of the above
191. How can you avoid making common mistakes when using control
flow statements?
a. Carefully consider the logic of your code before choosing a
control flow statement
b. Use break and continue statements judiciously
c. Test your code thoroughly to ensure that it is working as
expected
d. All of the above
194. What are some common mistakes that people make when using
break and continue statements in nested loops?
a. Not using break statements to terminate the outer loop when the
desired condition has been met
b. Not using continue statements to skip to the next iteration of the
inner loop when the desired condition has not been met
c. Using break and continue statements incorrectly, which can lead
to unexpected behavior
d. All of the above
195. How can you avoid making common mistakes when using break
and continue statements in nested loops?
a. Carefully consider the logic of your code before using break and
continue statements
b. Test your code thoroughly to ensure that it is working as
expected
c. Use break and continue statements judiciously
d. All of the above
196. How can you use a switch statement to control the flow of a
program?
a. By using the switch statement to execute different blocks of code
based on the value of an expression
b. By using the switch statement to iterate over a collection of
values
c. By using the switch statement to control the execution of other
control flow statements
d. All of the above
197. What are some common mistakes that people make when using
switch statements to control the flow of a program?
a. Not using a default case statement to handle unexpected values
b. Not using break statements to prevent the execution of
subsequent case statements
c. Using a switch statement when a different control flow statement,
such as an if statement or a for loop, would be more appropriate
d. All of the above
198. How can you avoid making common mistakes when using switch
statements to control the flow of a program?
a. Carefully consider the logic of your code before choosing a
switch statement
b. Use break statements to prevent the execution of subsequent case
statements
c. Use a default case statement to handle unexpected values
d. All of the above
200. What are some common design patterns that use control flow
statements?
a. The state pattern, the strategy pattern, and the template method
pattern
b. The observer pattern, the singleton pattern, and the factory
method pattern
c. The decorator pattern, the adapter pattern, and the facade pattern
d. All of the above
201. How can you use control flow statements to write more efficient
and maintainable code?
a. By using the appropriate control flow statement for the job
b. By using break and continue statements judiciously
c. By testing your code thoroughly to ensure that it is working as
expected
d. All of the above
214. Which of the following is a best practice for using control flow
statements in code?
a. Use the appropriate control flow statement for the job
b. Use break statements to terminate loops when the desired
condition has been met.
c. Use continue statements to skip to the next iteration of a loop
when the desired condition has not been met
d. All of the above
225. Which of the following is a good use case for the continue
statement?
a. To avoid writing nested loops.
b. To skip part of the loop body based on a condition.
c. To exit a loop early.
d. All of the above.
231. Can the switch statement be used to test a variable of any type?
a. Yes, the switch statement can be used to test a variable of any
type.
b. No, the switch statement can only be used to test variables of
integral types.
c. No, the switch statement can only be used to test variables of
character types.
d. No, the switch statement can only be used to test variables of
string types.
232. Can the switch statement be used to test a variable against a list of
ranges of values?
a. Yes, the switch statement can be used to test a variable against a
list of ranges of values.
b. No, the switch statement can only be used to test a variable
against a list of specific values.
c. Yes, but only if the variable is of an integral type.
d. Yes, but only if the variable is of a character type.
233. Which of the following is a good use case for the switch statement?
a. To implement a menu system.
b. To perform different actions based on the value of a variable.
c. To avoid writing nested if-else statements.
d. All of the above.
237. Which of the following is a good way to avoid writing nested if-
else statements using the switch statement?
a. Use a single case statement with multiple conditions.
b. Use a nested switch statement.
c. Use a table lookup instead of a switch statement.
d. All of the above.
248. Which of the following is a good use case for a for loop?
a. To iterate over a list of items
b. To execute a block of code a fixed number of times
c. Both a and b
d. None of the above
249. Which of the following is a good use case for a while loop?
a. To iterate over a list of items until a condition is met
b. To execute a block of code while a condition is true
c. Both a and b
d. None of the above
250. Which of the following is a good use case for a do-while loop?
a. To execute a block of code at least once and then as long as a
condition is true.
b. To iterate over a list of items until a condition is met.
c. Both a and b
d. None of the above
Conclusion
The development of MCQs, precisely target control flow statements, is a
noteworthy advancement in the realm of programming education. The
chapter is comprehensive and adaptable, enabling learners and instructors to
evaluate, strengthen, and enhance their comprehension of control flow, a
critical element in coding. These questions promote the development of
factual recall, critical thinking, and problem-solving abilities by covering
various control flow components and emphasizing their application in real-
world situations. Consequently, programming boot camps serve a crucial role
in imparting individuals with the necessary information and abilities to thrive
in programming and problem-solving, thereby fostering the expansion of a
worldwide network of adept and inventive programmers. The next chapter
will conduct a comprehensive analysis of MCQs pertaining to Python
functions.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
This chapter provides a comprehensive overview of Python functions through
multiple-choice questions. This chapter aims to test the reader’s
understanding of the fundamental concepts and principles related to Python
functions. By engaging in this interactive format, learners can assess their
knowledge and identify areas that require further study. The chapter covers
various aspects of Python functions, including function definition,
parameters, return values, and function calls. It is a valuable resource for
individuals looking to enhance their proficiency in Python programming and
strengthen their grasp of functions.
Objectives
This chapter aims to assess the reader’s comprehension and knowledge of
Python functions through a series of multiple-choice questions. By presenting
a range of questions related to function definition, parameters, return values,
and function calls, this chapter aims to evaluate the reader’s understanding of
these concepts.
11. What is the result of calling a function in Python that does not
have a return statement?
a. None c. True
b. 0 d. Error
12. Which of the following is not a valid way to define a function in
Python?
a. def my_function():
b. function my_function():
c. def my_function
d. def my_function(param1, param2):
40. Which one of the following is the correct way of calling a function?
a. function_name()
b. call function_name()
c. ret function_name()
d. function function_name()
48. Functions which are already defined in Python are called _____.
a. user defined function
b. library functions
c. built in functions
d. Both b and c
50. Functions that do not return any value are called ________.
a. default functions
b. zero functions
c. void functions
d. null functions
51. The __________ statement return the values from the function to
the calling function.
a. Send c. Return
b. Give d. Take
52. Choose the correct statement:
a. We can create function with no argument and no return value
b. We can create function with no argument and with return
value(s).
c. We can create function with arguments(s) and no return value.
d. All of the above.
53. A function may return multiple values using ______.
a. List c. String
b. Tuple d. Dictionary
54. The part of the program where a variable is accessible is known as
the _________ of the variable.
a. Scope c. Part
b. Module d. None of the above
55. Which of the following is not the scope of variable?
a. Local c. Outside
b. Global d. None of the above
56. Fill in the blank so that the output is 9:
a=9
def sound():
_____ a
print(a)
sound()
a. Local c. Outer
b. Global d. var
57. How many built-in functions are used in the following code:
a= int(input("Enter a number:"))
b=a*a
print("The square of",a," is",b)
a. 1 c. 3
b. 2 d. 4
58. Which of the following is not the built-in function?
a. input() c. print()
b. tuple() d. dictionary()
59. Which of the following is not the type of function argument?
a. Required argument
b. Keyword argument
c. initial argument
d. default argument
89. Which built-in function is used to find the maximum value from
an iterable (e.g., a list or tuple)?
a. max() c. find_max()
b. maximum() d. peak()
90. What does the type() function do in Python?
a. It converts a string to a numeric type (e.g., int or float)
b. It checks if a variable is of a specific type
c. It performs type casting
d. It creates a new type
95. Which built-in function is used to find the minimum value from an
iterable (e.g., a list or tuple)?
a. min() c. find_min()
b. minimum() d. bottom()
96. What does the join() function do in Python?
a. It performs string concatenation.
b. It creates a new list.
c. It merges multiple dictionaries.
d. It joins elements of an iterable with a specified string.
99. Which built-in function is used to find the index of the first
occurrence of a specified element in a list?
a. find_index()
b. first_index()
c. index()
d. search()
100. What does the zip() function do in Python?
a. It compresses files.
b. It unzips files.
c. It creates a zip archive.
d. It combines multiple iterables into a single iterable of tuples.
101. Which built-in function is used to open and read a file in Python?
a. open_file()
b. read_file()
c. file_open()
d. open()
111. Which built-in function is used to find the index of the first
occurrence of a specified element in a list?
a. find_index() c. search()
b. index() d. first_index()
112. What is the primary purpose of the bool() function in Python?
a. To calculate the boolean AND of two values.
b. To check if a value is zero.
c. To convert a value to a boolean type (True or False).
d. To perform logical OR operations.
137. Which built-in function is used to calculate the sum of all elements
in a list with a specific starting value?
a. sum() c. add_up()
b. calculate_sum() d. total()
138. What is the purpose of the all() function in Python?
a. To convert a list to a set.
b. To check if all elements in an iterable are True.
c. To create a new list.
d. To concatenate strings.
139. Which built-in function is used to find the most common element
in an iterable?
a. common_element()
b. most_common()
c. find_most()
d. frequency()
144. What does the open() function do in Python when used with the
“w” mode for file handling?
a. It opens an existing file for reading.
b. It opens a file for writing, creating a new file if it doesn’t exist.
c. It opens a file for reading and writing simultaneously.
d. It opens a file for appending data.
147. Which built-in function is used to find the most common element
in an iterable with a specified key function?
a. common_element()
b. most_common()
c. find_most()
d. frequency()
159. Which built-in function is used to find the index of the first
occurrence of a specified element in a list?
a. find_index() c. search()
b. index() d. first_index()
160. What is the primary purpose of the bool() function in Python?
a. To calculate the boolean AND of two values.
b. To check if a value is zero.
c. To convert a value to a boolean type (True or False).
d. To perform logical OR operations.
func(3, 7)
func(25, c =24)
func(c =50, a =100)
a. a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and cis 50
b. a is 3 and b is 7 and cis 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c. a is3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d. None
print(maximum(2,3))
a. 2
b. 3
c. The numbers are equal
d. None of the mentioned
176. Select all the parts that are absolutely needed to create and call a
function.
a. A function body and header
b. Variables
c. return statement
d. function call
179. What will be printed after calling divide (100, 95) and divide (5, 7)
and divide (7, 5) ?
def divide(num1,num2):
single_div_answer=num1/num2
print(round(single_div_answer,2))
double_div_answer=num1//num2
print(round(double_div_answer,2))
a. 1, 1.05, 0, 0.71, 1, 1.4
b. 1.05, 5, 0.71, 5, 1.4, 2
c. 1.05, 2, 0.71, 1, 1.4, 2
d. 1.05, 1, 0.71, 1, 1.4, 1
e. 1.05, 1, 0.71, 0, 1.4, 1
180. After running the following code, what will the output be?
def multiplication_one(num1,num2):
num1*num2
print(multiplication_one(5,10))
def multiplication_two(num1,num2):
returnnum1*num2
multiplication_two(5,10)
a. None will be outputted after printing and calling
multiplication_one(5, 10). Nothing will be outputted after calling
multiplication_two(5, 10).
b. Nothing will be outputted after printing and calling
multiplication_one(5, 10). None will be outputted after calling
multiplication_two(5, 10).
c. 50 will be outputted after printing and calling
multiplication_one(5, 10) and after calling multiplication_two(5,
10).
d. None will be outputted after printing and calling
multiplication_one(5, 10). 50 will be outputted after calling
multiplication_two(5, 10).
e. 50 will be outputted after printing and calling
multiplication_one(5, 10). Nothing will be outputted after calling
multiplication_two(5, 10).
191. Consider the code block below. What happens when you run this
program?
repeat_lyrics()
def repeat_lyrics():
print_lyrics()
print_lyrics()
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
a. The lyrics print like normal.
b. We get a TypeError.
c. We get a NameError.
d. The program compiles but nothing prints.
Conclusion
By actively participating in the MCQs, readers have gained valuable insights
into their proficiency in Python functions and can use this feedback to
enhance their skills. Overall, this chapter has provided a solid foundation for
mastering Python functions and serves as a stepping stone for further
exploration and growth in Python programming. The forthcoming chapter
will provide a complete analysis of MCQs related to Python Strings.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Strings are fundamental data types in Python, and understanding how to work
with them efficiently is essential for any programmer. This chapter focuses
on creating MCQs that specifically target Python’s sequence manipulation,
with a specific emphasis on string handling. The creation of MCQs revolving
around Python’s string handling is crucial in assessing, reinforcing, and
deepening one’s comprehension of this core aspect of the language. These
MCQs aim to serve as a valuable resource for learners, educators, and anyone
interested in mastering the intricacies of string manipulation in Python. The
availability of these MCQs contributes to the broader field of programming
education, emphasizing the value of interactive assessment tools in enhancing
learning outcomes.
Objectives
The primary objective of this chapter is to comprehensively assess and
reinforce learners’ understanding of Python’s string-handling capabilities.
These MCQs aim to cover various string manipulation aspects, such as string
methods, formatting, slicing, concatenation, and other crucial operations.
They serve not only to evaluate factual knowledge but also to prompt critical
thinking and problem-solving by presenting practical scenarios where string
manipulation skills are put to the test. Moreover, incorporating interactive
elements aims to enhance engagement and cater to various learning styles,
ensuring accessibility and effectiveness for a diverse audience, from
beginners to seasoned programmers seeking to master Python’s string
manipulation intricacies.
18. Which of the following is the correct way to access the last
character of a string in Python?
a. s[len(s)] c. s[-len(s)]
b. s[-1] d. s[0]
19. What is the output of the code "Python".find("th")?
a. 2 c. 3
b. 1 d. -1
20. What is the result of the expression "abc" * 3 in Python?
a. “abcabc”
b. “abc abc abc”
c. 9
d. [“abc”, “abc”, “abc”]
21. Which method is used to find the index of the first occurrence of a
substring in a string?
a. substring() c. find()
b. index() d. search()
22. What is the output of the code "Hello,
World!".count("l")?
a. 2 c. 4
b. 3 d. 5
23. Which of the following statements is true about Python strings?
a. Strings in Python can only contain alphabetic characters.
b. Strings are mutable, so you can change individual characters in a
string.
c. Strings can be enclosed in single or double quotes, but not triple
quotes.
d. Strings are iterable and can be indexed and sliced.
42. How can you find the position of the last occurrence of a substring
in a string in Python?
a. Using the find() method
b. Using the rfind() method
c. Using the search() method
d. Using the locate() method
60. How can you check if a string contains only uppercase letters in
Python?
a. Using the isuppercase() method
b. Using the isupper() method
c. Using the uppercase() method
d. There is no built-in method for this in Python.
93. How can you remove whitespace characters from the left side of a
string in Python?
a. Using the trim() method
b. Using the clear() method
c. Using the lstrip() method
d. Using the remove() method
108. How can you check if a string contains only alphabetic characters
(letters) and does not include any other characters in Python?
a. Using the isalpha() method
b. Using the isletter() method
c. Using the isalphabetic() method
d. Using the alpha() method
121. How can you check if a string is composed of only lowercase letters
(a-z) and underscores (_) in Python?
a. Using the islower() method
b. Using the isalpha() method
c. Using the islowerunderscore() method
d. Using the isvalididentifier() method
175. How can you concatenate multiple strings into one in Python?
a. Using + operator
b. Using & operator
c. Using concat() method
d. Using join() method
180. In Python, which of the following will extract the last character of
a string?
a. string[0]
b. string[-1]
c. string[-2]
d. string[len(string)]
181. Which method is used to find the index of the first occurrence of a
substring in a string?
a. find() c. index()
b. search() d. locate()
182. What will string.count("o") return in the string "Hello,
world!"?
a. 0 c. 2
b. 1 d. 4
183. Which method is used to replace a substring with another
substring in a string?
a. replace()
b. substitute()
c. swap()
185. How can you check if a string ends with a specific suffix in
Python?
a. string.ends()
b. string.endswith()
c. string.endswithwith()
d. string.isendwith()
186. What does the strip() method do for strings in Python?
a. Removes all leading and trailing spaces.
b. Removes all spaces from the middle of the string.
c. Adds spaces to the beginning and end of the string.
d. Converts the string to uppercase.
199. Which method can be used to compare two strings while ignoring
their letter case?
a. compare()
b. equalsIgnoreCase()
c. case_insensitive_compare()
d. compare_ignore_case()
201. How can you remove leading and trailing whitespace from a
string?
a. strip()
b. remove_whitespace()
c. trim()
d. clear()
202. What method can be used to check if a string contains only digits?
a. isalpha() c. isnumeric()
b. isdigit() d. isnumber()
203. Which method can be used to convert a string to a list of
characters?
a. tolist() c. list()
b. split() d. explode()
204. How can you remove a specific character from a string?
a. remove() c. replace()
b. delete() d. discard()
205. What does the join() method do in Python?
a. Combines elements of a list into a single string.
b. Joins two strings together.
c. Removes a substring from a string.
d. Splits a string into a list.
208. Which method is used to find the last index of the first occurrence
of a substring in a string?
a. find() c. rfind()
b. index() d. rindex()
209. What is the output of string.find("Python") if “Python” is
not present in string?
a. 0 c. None
b. -1 d. An error
210. Which method of string returns the index number if it contains a
given substring?
a. Using string.index(substring)
b. Using string.contains(substring)
c. Using substring.in(string)
d. Using substring.search(string)
215. How can you concatenate a list of strings into a single string in
Python?
a. Using join() method
b. Using concat() method
c. Using + operator
d. Using merge() function
228. Which operator can be used to check if two strings are not equal
in Python?
a. <> c. ==
b. != d. =~
229. How can you compare two strings by their values and ignore their
letter case?
a. str1.equalsIgnoreCase(str2)
b. str1.compareIgnoreCase(str2)
c. str1.case_insensitive_compare(str2)
d. str1.lower() == str2.lower()
231. How can you remove all whitespace characters from a string in
Python?
a. trim()
b. strip()
c. remove_whitespace()
d. delete_whitespace()
236. Which method returns the first index of the last occurrence of a
substring in a string, or -1 if not found?
a. find() c. rfind()
b. index() d. rindex()
237. What is the output of string.find("Python") if “Python” is
not present in string?
a. 0 c. None
b. -1 d. An error
238. How can you check if a string contains a specific substring and get
its index if found?
a. Using string.index(substring)
b. Using string.contains(substring)
c. Using substring.in(string)
d. Using substring.search(string)
240. How can you extract a substring from the end of a string in
Python?
a. Using substring(start, end)
b. Using negative indices
c. Using substringFromEnd(start, end)
d. Using the rsubstring() method
244. How can you concatenate a list of strings into a single string in
Python?
a. Using join() method
b. Using concat() method
c. Using + operator
d. Using merge() function
Conclusion
This chapter focuses on handling sequences and strings in Python, a
fundamental aspect of programming instruction. The MCQs provided are a
valuable resource for learners to evaluate, strengthen, and enhance their
comprehension of Python’s string manipulation, a key aspect of the
programming language. These inquiries foster the development of critical
thinking and problem-solving abilities by including a wide array of string
operations and prompting learners to apply this knowledge to real-world
situations. By integrating interactive components, these questions boost user
engagement and cater to a wide range of learning preferences, promoting
inclusivity and accessibility for a varied audience. The forthcoming chapter
will provide a complete analysis of MCQs related to Python Lists.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
This chapter offers a detailed examination of many topics presented in a
concise and structured way. Lists are crucial for efficient learning as they
provide a structured analysis of information, which helps with memory and
understanding. This chapter covers a variety of topics, offering readers a
great resource to strengthen their grasp of important concepts. The
meticulously selected lists encompass a wide range of subjects, guaranteeing
a comprehensive approach to gaining knowledge. We are also provided with
a systematic and accessible framework for students and hobbyists to learn
and review vital content, ranging from fundamental principles to advanced
ideas. This chapter is essential for individuals seeking to efficiently grasp the
subject matter, whether as a quick reference or a study aid.
Objectives
The objectives of this chapter in this MCQ book are to offer a structured
presentation of diverse topics, enabling quick reference and comprehensive
revision for improved information retention. The chapter accommodates
various learning styles by breaking down intricate concepts into manageable
lists. It functions as a versatile resource, catering to the needs of students,
professionals, and enthusiasts alike, providing a condensed yet
comprehensive overview of the subject matter.
Multiple choice questions
1. Which of the following commands will create a list?
a. list1 = list()
b. list1 = []
c. list1 = list([1, 2, 3])
d. all of the mentioned
4. What is the correct way to access the third element in a list named
my_list?
a. my_list[2] c. my_list{2}
b. my_list(2) d. my_list.2
5. In Python, how can you check if an element exists in a list?
a. element in list
b. list.contains(element)
c. list.has(element)
d. element.exists(list)
6. What is the purpose of the pop() method in lists?
a. Removes the first element of the list
b. Removes the last element of the list
c. Removes an element at a specified index
d. Removes all occurrences of a specified element
10. What happens if you try to concatenate two lists using the +
operator?
a. It creates a new list with elements from both lists
b. It raises an error because lists cannot be concatenated
c. It adds the elements of the second list to the first list
d. It only concatenates the last elements of both lists
13. What does the sorted() function return when applied to a list ?
a. The original list in ascending order
b. A new list containing the elements in descending order
c. A new list containing the elements in ascending order
d. The original list with no changes
21. If a list has a length of 6, what is the valid index range for the list?
a. 0 to 6
b. 1 to 5
c. -6 to 6
d. 0 to 5
24. If you want to split a string into a list of characters, what should
be used as the delimiter?
a. str.split(‘’)
b. str.split()
c. list(str)
d. str.split(None)
25. How can you limit the number of splits performed by the
split() method in Python?
a. str.split(limit)
b. str.split(maxsplit=limit)
c. str.split(0, limit)
d. str.split(1, limit)
30. How can you insert a new element at a specific index in a list,
shifting the existing elements to make room?
a. list.add(index, new_element)
b. list.insert(index, new_element)
c. list.place(index, new_element)
d. list.shift(index, new_element)
33. What is the result of using the + operator to concatenate two lists?
a. Creates a new list with elements from both lists
b. Adds the elements of the second list to the first list
c. Raises an error because lists cannot be concatenated
d. Multiplies the elements of the second list with the elements of the
first list
38. How can you iterate through both the index and the elements of a
list simultaneously?
a. for i in range(len(list))
b. for element in enumerate(list):
c. for i, element in list:
d. for element in list.index():
39. What is the purpose of the zip() function when iterating through
multiple lists?
a. Combines the lists into a single list
b. Creates a zip file containing the lists
c. Iterates through corresponding elements of multiple lists
simultaneously
d. Unzips a compressed list
40. What does the reversed() function do when applied to a list
during iteration?
a. Reverses the order of the elements in the list
b. Sorts the list in descending order
c. Creates a reversed copy of the list
d. Raises an error, as reversed() is not applicable to lists
41. How can you break out of a loop during iteration when a certain
condition is met?
a. break(list)
b. stop_iteration()
c. exit()
d. break
55. How can you find the position of the first occurrence of a specified
element in a list?
a. position(list, element)
b. list.first_position(element)
c. find_first(list, element)
d. list.index(element)
56. Which method is used to remove the last element from a list?
a. list.remove_last()
b. list.pop()
c. list.delete_last()
d. remove_last(list)
60. Which built-in function can be used to find the sum of elements in
a list?
a. total(list)
b. add(list)
c. sum(list)
d. list.sum()
63. Which function is used to find the position of the last occurrence of
a specified element in a list?
a. last_position(list, element)
b. list.last_position(element)
c. find_last(list, element)
d. list.rindex(element)
66. Which function is used to find the difference between two lists?
a. list.difference(other_list)
b. list.subtract(other_list)
c. difference(list, other_list)
d. list - other_list
73. Which of the following is the correct way to call the function
calculate_sum with arguments 3 and 5?
a. calculate_sum(3, 5)
b. calculate_sum(3 + 5)
c. calculate_sum(3, + 5)
d. calculate_sum(3 + 5,)
88. Which of the following statements correctly uses if-else with a list
comprehension?
a. [x if x > 0 else 0 for x in numbers]
b. [x > 0 else 0 for x in numbers]
c. [if x > 0: x else: 0 for x in numbers]
d. [x for x in numbers if x > 0 else 0]
92. You have a list named students representing student names. How
can you add a new student named “Alice” to the list?
a. students.add(“Alice”)
b. students.append(“Alice”)
c. students.insert(“Alice”)
d. students.extend(“Alice”)
93. You have a list called prices containing the prices of different
products. How can you find the average price of the products?
a. sum_prices = sum(prices) / len(prices)
b. avg_price = average(prices)
c. avg_price = prices.mean()
d. avg_price = prices / len(prices)
94. You have a list representing temperatures in Celsius. How can you
convert all temperatures to Fahrenheit using a list
comprehension?
a. [temp * (9/5) + 32 for temp in temperatures]
b. [temp + 32 * (9/5) for temp in temperatures]
c. [temp * 9/5 + 32 for temp in temperatures]
d. [temp + 32 for temp in temperatures]
95. If you want to remove all duplicate elements from a list named
items, what is an efficient way to achieve this?
a. items = set(items)
b. items = list(set(items))
c. items.remove_duplicates()
d. items = items.unique()
96. You have a list called grades representing student grades. How
can you create a new list containing only passing grades (grades
>= 60)?
a. [grade for grade in grades if grade >= 60]
b. [grade if grade >= 60 else “Pass” for grade in grades]
c. [grade > 60 for grade in grades]
d. grades.filter(grade >= 60)
97. You have a list named sales representing monthly sales figures;
how can you find the month with the highest sales?
a. max_month = max(sales)
b. max_month = sales.index(max(sales))
c. max_month = sales.month_with_max()
d. max_month = sales.max_month()
101. You have two lists, list1 and list2, representing items in two
different categories. How can you combine them into a single list?
a. list1.add(list2)
b. list1 + list2
c. list1.combine(list2)
d. list1.extend(list2)
116. How do you use the reduce() function to find the product of
elements in a list?
a. reduce(multiply, lst)
b. reduce(product, lst)
c. reduce(lambda x, y: x * y, lst)
d. reduce(prod, lst)
121. What does the min() function return when applied to a list of
strings?
a. The shortest string
b. The longest string
c. The string with the smallest ASCII value
d. The string with the largest ASCII value
124. How is the length of a list calculated using the len() function?
a. By counting the number of elements in the list
b. By summing up the elements in the list
c. By finding the average of elements in the list
d. By checking the presence of elements in the list
128. How is the map() function used to square each element in a list?
a. map(square, lst)
b. map(lambda x: x ** 2, lst)
c. map(squared, lst)
d. map(pow(2), lst)
130. When using the lambda function, what is the correct syntax for a
function that adds two numbers?
a. lambda x, y: x + y
b. lambda add(x, y): x + y
c. lambda (x, y): x + y
d. lambda add(x + y)
132. The sum() function can be used with an iterable other than lists.
What is the primary requirement for the iterable?
a. It must be a tuple
b. It must be a set
c. It must be a string
d. It must contain numeric elements
133. What does the all() function return when applied to an empty
list?
a. True
b. False
c. None
d. It raises an error
137. When using the map() function, what is the result of mapping
the int function to a list of strings?
a. The list of strings remains unchanged
b. Each string in the list is converted to an integer
c. The list is reversed
d. The list is sorted alphabetically
139. What is the primary purpose of the max() function when applied
to a list of strings?
a. Finds the shortest string
b. Finds the longest string
c. Sorts the strings alphabetically
d. Reverses the order of strings
140. How is the min() function used with a custom function when
applied to a list of tuples?
a. min(list, key=lambda x: x[0])
b. minimum(list, key=lambda x: x[1])
c. find_min(list, key=lambda x: x[0])
d. min_element(list, key=lambda x: x[1])
142. What does the any() function return when applied to an empty
list?
a. True
b. False
c. None
d. It raises an error
143. How does the len() function behave when applied to a list of
nested lists?
a. Counts the number of nested lists
b. Counts the total number of elements in all nested lists
c. Counts the number of elements in the outer list
d. Returns the length of the first nested list
146. When using the filter() function with a lambda function, what
does the lambda function represent?
a. The condition for inclusion in the filtered list
b. The condition for exclusion from the filtered list
c. The function to be applied to each element
d. The key for sorting the filtered list
147. What does the map() function return when applied to an empty
list?
a. An empty list
b. None
c. An error
d. A list containing the value 0
148. The lambda function is limited in terms of complexity compared to
regular functions.
a. True
b. False
c. It depends on the use case
d. There is no difference in complexity
149. What is the primary use case for the reduce() function?
a. Applying a function to each element in a list
b. Combining elements of a list using a specified function
c. Filtering elements based on a condition
d. Sorting elements in a list
153. What does the any() function return when applied to an empty
list?
a. True
b. False
c. None
d. It raises an error
154. How does the len() function behave when applied to a list of
nested lists?
a. Counts the number of nested lists
b. Counts the total number of elements in all nested lists
c. Counts the number of elements in the outer list
d. Returns the length of the first nested list
157. When using the filter() function with a lambda function, what
does the lambda function represent?
a. The condition for inclusion in the filtered list
b. The condition for exclusion from the filtered list
c. The function to be applied to each element
d. The key for sorting the filtered list
158. What does the map() function return when applied to an empty
list?
a. An empty list
b. None
c. An error
d. A list containing the value 0
163. If cmp() function is not used, then what is the alternative way for
comparing two list elements??
a. Using the comparison() function
b. Using the compare() function
c. Using the == operator directly
d. Using the cmp_to_key() function
165. What does the min() function return when applied to a list of
dictionaries?
a. The dictionary with the smallest key
b. The dictionary with the largest key
c. The dictionary with the smallest value
d. The dictionary with the largest value
170. How does the filter() function behave when applied to a list of
non-boolean elements without a specified function?
a. It raises an error
b. It filters out elements equal to None
c. It includes all elements in the filtered list
d. It applies the bool() function to each element
173. What is the primary use case for the any() function when applied
to a list of boolean values?
a. Checking if all values are True
b. Checking if any value is True
c. Counting the number of True values
d. Creating a new list with True values only
178. What is the purpose of the len() function when applied to a list
of tuples?
a. Counts the number of tuples in the list
b. Counts the total number of elements in all tuples
c. Counts the number of elements in the first tuple
d. Returns the length of the first element in each tuple
179. When using the enumerate() function, what is the data type of
the returned elements?
a. Tuple
b. List
c. Dictionary
d. Set
180. How does the max() function behave when applied to a list of
strings?
a. Returns the longest string
b. Returns the string with the smallest ASCII value
c. Returns the string with the largest ASCII value
d. Raises an error since strings are not comparable
186. When using the map() function, what is the result of mapping the
str function to a list of integers?
a. A list of strings representing the integers
b. A list of integers
c. A single concatenated string of integers
d. An error since str cannot be applied to integers
190. What is the purpose of the any() function when applied to a list
of boolean values?
a. Checking if all values are True
b. Checking if any value is True
c. Counting the number of True values
d. Creating a new list with True values only
196. What is the primary use case for the any() function when
applied to a list of boolean values?
a. Checking if all values are True
b. Checking if any value is True
c. Counting the number of True values
d. Creating a new list with True values only
202. If you want to calculate the average temperature for a week, which
function prototype would you use?
a. def calculate_average_temperature(temperatures):
b. def average(temperature_list):
c. def find_average(temps):
d. def avg_temp(weekly_temps):
203. You have a list of product prices, and you want to find and display
the most expensive product. What function would you implement?
a. def find_max_price(products):
b. def display_most_expensive(prices):
c. def max_product_price(items):
d. def highest_price(products_list):
204. Which function prototype would you need to use to remove all
occurrences of a specific element from a list?
a. def remove_element(my_list, target):
b. def delete_occurrences(elements, item):
c. def filter_list(input_list, value):
d. def eliminate(target, list_items):
205. You want to create a function that squares each element of a given
list and returns a new list containing the squared values. What
would be the function signature?
a. def square_elements(input_list):
b. def calculate_squares(numbers):
c. def square_list(lst):
d. def perform_square(list_values):
206. You are building a shopping cart application and need to add a
new item to the user’s cart. What function prototype would you
use?
a. def add_item_to_cart(cart, new_item):
b. def insert_cart_item(product, user_cart):
c. def update_cart_with(new_product):
d. def append_to_cart(shopping_cart, item):
208. You need to merge two lists and remove any duplicates; what
function prototype is suitable for this task?
a. def merge_and_remove_duplicates(list1, list2):
b. def combine_lists(unique_merge):
c. def merge_lists_remove_duplicates(first, second):
d. def merge_with_no_duplicates(list_one, list_two):
210. You have a list of students’ exam scores, and you want to find the
average score excluding the lowest and highest scores. What
function would you implement?
a. def calculate_average_without_extremes(scores):
b. def find_middle_average(exam_results):
c. def exclude_extremes_and_average(results):
d. def average_excluding_outliers(student_scores):
211. You are building a social media application and want to filter out
posts containing offensive words from a user’s timeline; what
function prototype would you use?
a. def filter_offensive_posts(user_timeline, forbidden_words):
b. def screen_posts_for_offensive_words(posts, bad_words):
c. def sanitize_timeline(timeline, offensive_terms):
d. def remove_offensive(timeline, words_to_exclude):
212. You want to create a function to find the most common element in
a list. What would be the function signature?
a. def find_most_common(lst):
b. def common_element_finder(elements):
c. def identify_common_value(items_list):
d. def most_frequent_element(data):
216. You are developing a game and need to shuffle a list of questions
to present them in a random order; what function would you
create?
a. def shuffle_questions(question_list):
b. def randomize_questions(questions):
c. def mix_question_order(quiz):
d. def reorder_questions(random_list):
217. You have a list of employee salaries, and you want to find the
difference between the highest and lowest salaries. What function
signature would you use?
a. def salary_range(salaries):
b. def calculate_salary_difference(payroll):
c. def find_salary_variation(employee_salaries):
d. def range_of_salaries(salary_list):
218. You want to filter out all even numbers from a list of integers.
What function prototype would you use?
a. def filter_even_numbers(number_list):
b. def exclude_odds(numbers):
c. def remove_odd_values(data):
d. def select_even_elements(integers):
219. You need to create a function that appends a new element to a list
only if it is not already present. What function prototype would
you use?
a. def append_unique_element(my_list, new_element):
b. def add_element_unless_exists(elements, item):
c. def insert_if_not_present(input_list, value):
d. def unique_append(target, list_items):
220. You have a list of book titles, and you want to find and display the
longest title. What function would you implement?
a. def find_longest_title(book_titles):
b. def display_max_length_title(titles):
c. def longest_book_title(books):
d. def identify_longest(book_titles_list):
221. You are developing a search engine and want to remove common
stop words from a list of search query terms. What function
prototype would you use?
a. def remove_stop_words(query_terms, stop_words):
b. def filter_common_terms(terms, stop_list):
c. def clean_search_query(query, common_words):
d. def eliminate_stopwords(search_terms, common_terms):
222. You want to create a function that concatenates two lists and
removes any duplicates. What would be the function signature?
a. def merge_and_remove_duplicates(list1, list2):
b. def combine_lists(unique_merge):
c. def merge_lists_remove_duplicates(first, second):
d. def merge_with_no_duplicates(list_one, list_two):
223. What function prototype would you use to find the median value
of a list of numbers?
a. def find_median(numbers):
b. def calculate_list_median(data):
c. def identify_median_value(values):
d. def median_of_list(lst):
224. You have a list of distances in kilometers, and you want to convert
them to miles using a conversion factor. What function would you
create?
a. def convert_to_miles(distance_list, conversion_factor):
b. def miles_conversion(distances, factor):
c. def km_to_miles_converter(distances, conversion):
d. def perform_distance_conversion(km_distances, factor):
226. You are developing a weather application and want to filter out
temperatures below freezing from a list. What function prototype
would you use?
a. def filter_freezing_temps(temperature_list):
b. def remove_cold_temps(temperatures):
c. def exclude_below_freezing(degrees):
d. def select_non_freezing(temperature_values):
227. What function prototype would you use to create a function that
checks if a given list is sorted in ascending order?
a. def is_sorted_ascending(input_list):
b. def check_sort_order(data):
c. def validate_sorting(order_list):
d. def verify_ascending_sequence(sequence):
229. What function prototype would you use if you are developing a
calendar application and need to find the number of events
scheduled for a particular date?
a. def count_events_for_date(events, target_date):
b. def find_date_occurrences(schedule, date):
c. def identify_event_count(events_list, specified_date):
d. def check_events_on_date(event_list, target_date):
230. You have a list of car prices, and you want to filter out the ones
above a certain budget limit. What function would you
implement?
a. def filter_expensive_cars(car_prices, budget_limit):
b. def remove_overpriced(cars, max_price):
c. def exclude_high_priced(cars_list, threshold):
d. def select_affordable_cars(prices, limit):
231. You want to create a function to find and display the most
common character in a list of strings; what function signature
would you use?
a. def find_most_common_character(strings):
b. def display_max_occurrence(characters):
c. def most_common_string_char(words):
d. def identify_most_common_char(char_list):
232. You are building a voting system, and you need to check if a
candidate has reached a required number of votes to win; what
function prototype would you use?
a. def check_win_condition(candidate_votes, required_votes):
b. def validate_candidate_victory(votes, threshold):
c. def verify_win(candidate_votes_list, required_count):
d. def has_reached_required_votes(vote_count, required_votes):
233. You have a list of file sizes, and you want to find the total size in
megabytes; what function would you create?
a. def calculate_total_size(file_sizes):
b. def find_total_megabytes(sizes):
c. def determine_file_size(total_sizes):
d. def sum_file_sizes(file_size_list):
234. You need to create a function that appends a new element to a list
only if it’s not already present; what function prototype would you
use?
a. def append_unique_element(my_list, new_element):
b. def add_element_unless_exists(elements, item):
c. def insert_if_not_present(input_list, value):
d. def unique_append(target, list_items):
235. You have a list of employee salaries, and you want to find the
difference between the highest and lowest salaries; what function
signature would you use?
a. def salary_range(salaries):
b. def calculate_salary_difference(payroll):
c. def find_salary_variation(employee_salaries):
d. def range_of_salaries(salary_list):
236. What function prototype would you use to create a function that
checks if a given list is sorted in descending order?
a. def is_sorted_descending(input_list):
b. def check_sort_order(data):
c. def validate_sorting(order_list):
d. def verify_descending_sequence(sequence):
237. What function prototype would you use if you want to calculate
the overall performance of students based on their scores in
different subjects?
a. def calculate_overall_performance(subject_scores, weights):
b. def analyze_subjects_performance(scores, subjects):
c. def evaluate_student_performance(student_scores,
subject_weights):
d. def find_overall_grade(score_list, weight_list):
239. What function would you implement if you are building a music
player and need to find the total duration of a playlist?
a. def calculate_total_duration(song_durations):
b. def find_playlist_duration(durations):
c. def determine_total_playtime(songs):
d. def sum_song_durations(duration_list):
240. You want to create a function that filters out all elements in a list
that do not satisfy a certain condition; what function prototype
would you use?
a. def filter_elements(input_list, condition):
b. def exclude_non_matching(elements, criteria):
c. def remove_unwanted(list_data, filter_condition):
d. def select_matching_elements(data_list, condition):
241. You have a list of movie ratings, and you want to find and display
the highest-rated movie; what function would you implement?
a. def find_highest_rated(movies_ratings):
b. def display_best_movie(ratings):
c. def highest_rated_movie(movies):
d. def identify_top_rated(movie_ratings_list):
243. You are developing a chat application and need to filter out
messages that contain inappropriate words; what function
prototype would you use?
a. def filter_inappropriate_messages(chat_history,
forbidden_words):
b. def screen_messages_for_inappropriate_content(messages,
bad_words):
c. def sanitize_chat(chat_history, offensive_terms):
d. def remove_inappropriate(chat_messages, words_to_exclude):
245. If you need to create a function that computes the cumulative sum
of a list of numbers, what function prototype would you use?
a. def compute_cumulative_sum(number_list):
b. def find_cumulative_total(numbers):
c. def determine_running_total(data):
d. def accumulate_list_values(lst):
246. You are building a quiz application and need to shuffle a list of
questions to present them in a random order, what function would
you create?
a. def shuffle_questions(question_list):
b. def randomize_questions(questions):
c. def mix_question_order(quiz):
d. def reorder_questions(random_list):
247. You have a list of exam scores, and you want to find and display
the lowest score, what function would you implement?
a. def find_lowest_score(scores):
b. def display_min_score(exam_scores):
c. def lowest_exam_score(scores_list):
d. def identify_least_score(results):
249. You need to create a function that appends a new element to a list
only if it’s not already present, what function prototype would you
use?
a. def append_unique_element(my_list, new_element)
b. def add_element_unless_exists(elements, item)
c. def insert_if_not_present(input_list, value)
d. def unique_append(target, list_items)
250. If you have a list of customer ages, and you want to find the
average age of the customers, what function would you create?
a. def calculate_average_age(customer_ages):
b. def find_average_age(ages):
c. def determine_age_average(age_list):
d. def avg_customer_age(customer_list):
Conclusion
In summary, this chapter serves as a significant resource for facilitating
efficient learning and preserving information. By means of its methodical
exposition of a wide range of subjects, the chapter not only enables effortless
referencing and thorough review, but also accommodates the diverse learning
preferences of its audience. It guarantees clarity without jeopardizing
substance by deconstructing intricate ideas into feasible enumerations. The
List Chapter is an indispensable resource for professionals seeking a concise
review, students striving for exam success, and enthusiasts desiring a
comprehensive yet consolidated understanding of the subject. Fundamentally,
this chapter makes a substantial contribution to the overall efficacy and
practicality of the MCQ book, thereby augmenting the educational experience
for a wide range of readers.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
The Python Tuples MCQ chapter is a comprehensive exploration of the tuple
data structure, thoroughly examining its properties and functionalities. This
chapter is crafted to help readers grasp the fundamentals of tuples in Python,
covering essential topics such as tuple creation, indexing, slicing, and the
unique characteristics distinguishing tuples from other data structures. The
MCQs within this chapter are strategically designed to assess readers’
understanding of tuple concepts and their ability to apply this knowledge in
practical scenarios. Moreover, the chapter explores advanced aspects of
tuples, including tuple unpacking, immutability, and tuple methods. By
engaging with the MCQs, readers can reinforce their comprehension of
Python tuples, making this chapter an invaluable resource for learners and
practitioners seeking a solid foundation in this critical data structure within
the Python programming language.
Objectives
The primary goal of this chapter is to introduce readers to the fundamental
concepts of tuples, including their creation, indexing, and slicing, fostering a
solid foundation in tuple manipulation. The chapter aims to deepen the
understanding by exploring more advanced features such as tuple unpacking,
immutability, and specialized tuple methods, ensuring readers are well-versed
in the diverse capabilities of this data structure. Additionally, the chapter
seeks to enhance problem-solving skills by presenting practical scenarios
where tuples play a crucial role.
34. Which method is used to remove the last element from a tuple?
a. delete() c. pop()
b. remove() d. discard()
35. What is the purpose of the max function in relation to tuples?
a. To find the maximum value in the tuple
b. To find the minimum value in the tuple
c. To find the sum of all values in the tuple
d. To find the average value in the tuple
36. Which of the following statements is true about the count method
in tuples?
a. It counts the total number of elements in the tuple
b. It counts the number of occurrences of a specified element
c. It counts the sum of all elements in the tuple
d. It counts the average value in the tuple
44. Which of the following is a valid way to check if two tuples are
equal?
a. tuple1.equals(tuple2)
b. tuple1 == tuple2
c. tuple1.compare(tuple2)
d. tuple1.is_equal(tuple2)
55. Which method is used to find the index of the first occurrence of a
specific element in a tuple?
a. find() c. search()
b. index() d. locate()
56. What is the result of ('a', 'b') * 3?
a. (‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’)
b. (‘a’, ‘b’, 3)
c. (‘a’, ‘b’, ‘a’, ‘b’, 3)
d. (‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’)
67. What is the purpose of the sorted function in the context of tuples?
a. To sort the elements in ascending order
b. To sort the elements in descending order
c. To remove duplicates from the tuple
d. To reverse the order of elements
70. How do you extract the last element from a tuple named
my_tuple?
a. my_ tuple. get(-1)
b. my _tuple. last()
c. my_ tuple. pop()
d. my_ tuple[-1]
76. Which method is used to check if all elements in a tuple are true?
a. all()
b. any()
c. is_ true()
d. check _all()
83. How do you check if two tuples, tup1 and tup2, are equal?
a. tup1 == tup2
b. tup1.equals(tup2)
c. tup1.compare(tup2)
d. equals(tup1, tup2)
105. In Python, what does the len() function return when called on a
dictionary?
a. The number of elements in the dictionary
b. The sum of all values in the dictionary
c. The number of keys in the dictionary
d. The length of the longest key in the dictionary
113. What is the correct syntax to create a tuple with a single element?
a. single_element_tuple = (1)
b. single_element_tuple = 1,
c. single_element_tuple = (1,)
d. single_element_tuple = (1, 2)
123. Which method is used to find the index of the first occurrence of a
specific element in a tuple?
a. tuple.index(element)
b. tuple.find(element)
c. index(tuple, element)
d. element.indexOf(tuple)
131. What is the purpose of the sum() function when used with a tuple
in Python?
a. It calculates the sum of all elements in the tuple
b. It returns the total number of elements in the tuple
c. It finds the maximum value in the tuple
d. It converts the tuple to a list
138. What is the purpose of the any() function when used with a tuple
in Python?
a. It checks if all elements in the tuple are True
b. It checks if any element in the tuple is True
c. It returns the smallest element in the tuple
d. It counts the occurrences of a specific element
151. How do you check if two tuples have at least one common element
in Python?
a. if tuple1.has_common_element(tuple2):
b. if any(element in tuple1 for element in tuple2):
c. if tuple1.common_elements(tuple2):
d. if tuple1.is_common(tuple2)\
153. How can you find the maximum element in a tuple in Python?
a. max_element(tuple)
b. tuple.max()
c. max(tuple)
d. tuple.find_max()
155. How do you create a tuple with repeated elements and a specific
length in Python?
a. tuple.repeat(3, element)
b. tuple.repeat(element, 3)
c. (element,) * 3
d. tuple.create(element, 3)
161. How do you find the sum of all elements in a tuple in Python?
a. tuple.sum()
b. sum(tuple)
c. tuple.calculate_sum()
d. calculate(tuple, sum)
168. What does the max() function return when applied to a tuple of
strings?
a. The maximum length of the strings.
b. The string with the highest ASCII value.
c. The string with the lowest ASCII value.
d. The first string in lexicographical order.
171. Which of the following methods returns the index of the last
occurrence of a specified element in a tuple?
a. last_index() c. find_last()
b. rindex() d. search_last()
172. In Python, can a tuple be used as a key in a dictionary?
a. Yes
b. No
c. Only if it contains integers
d. Only if it contains strings
174. What will be the output of the code print(3 * (1, 2))?
a. (3, 6) c. 6
b. (1, 2, 1, 2, 1, 2) d. Error
175. How can you find the number of occurrences of a specific element
in a tuple without using the count() method?
a. Using a loop and conditional statements.
b. Using the len() function.
c. Using the occurrences() method.
d. It’s not possible without count()
185. How can you convert a tuple of strings into a single string with
elements separated by a comma?
a. ‘,’.join(tuple)
b. tuple.Join(‘,’)
c. concat(tuple, ‘,’)
d. tuple.Concatenate(‘,’)
190. How can you convert a tuple of numbers into a tuple of their
squares?
a. tuple ** 2
b. (x**2 for x in tuple)
c. tuple.map(lambda x: x**2)
d. tuple.square()
193. How do you check if all elements in a tuple are of the same data
type?
a. Using the same_type() method.
b. Comparing the types of the first and last elements.
c. Looping through the tuple and checking each element’s type.
d. It’s not possible to check for the same data type in a tuple.
194. If tuple1 = (10, 20, 30) and tuple2 = (40, 50), what
is the result of the expression tuple1 * 2 + tuple2?
a. (10, 20, 30, 10, 20, 30, 40, 50)
b. (20, 40, 60, 40, 50)
c. (10, 20, 30, 40, 50)
d. Error
196. How can you create a tuple with repeated elements using the *
operator?
a. tuple(3 * (1, 2))
b. tuple((1, 2) * 3)
c. tuple((1, 2) ** 3)
d. tuple(3, (1, 2))
200. How can you convert a tuple of integers into a tuple of their
absolute values?
a. tuple.map(abs, integer_tuple)
b. tuple(abs(integer) for integer in integer_tuple)
c. tuple.integer_tuple(abs)
d. tuple.abs(integer_tuple)
201. How do you convert a tuple of strings into a tuple of their lengths?
a. tuple.lengths(tuple_of_strings)
b. tuple(len(s) for s in tuple_of_strings)
c. tuple_of_strings.length()
d. tuple(tuple_of_strings).lengths()
203. How can you remove the last element from a tuple?
a. tuple.pop()
b. del tuple[-1]
c. tuple.remove_last()
d. Tuples are immutable; elements cannot be removed.
205. How can you count the number of occurrences of each unique
element in a tuple?
a. tuple.count_duplicates()
b. tuple(Counter(tuple).items())
c. tuple.unique_counts()
d. tuple.frequency()
208. How can you convert a list of tuples into a single tuple?
a. tuple(list_of_tuples)
b. tuple(*list_of_tuples)
c. tuple.from_list(list_of_tuples)
d. tuple.concat(list_of_tuples)
215. Which of the following methods is used to remove the last element
from a tuple?
a. remove()
b. pop()
c. delete()
d. discard()
221. Which of the following is the correct way to create a tuple with
repeated elements?
a. repeated_tuple = (1, 2) * 3
b. repeated_tuple = (1, 2).repeat(3)
c. repeated_tuple = (1, 2).copy(3)
d. repeated_tuple = (1, 2).repeated(3)
229. How do you check if two tuples have the same length?
a. len(tuple1) == len(tuple2)
b. tuple1.length() == tuple2.length()
c. tuple1.size() == tuple2.size()
d. length(tuple1) == length(tuple2)
233. Which method is used to return the difference between two tuples?
a. difference() c. subtract()
b. diff() d. tuple1 - tuple2
234. How do you check if a tuple is empty?
a. if tuple.is_empty():
b. if len(tuple) == 0:
c. if not tuple:
d. Both b and c
235. How do you find the common elements between two tuples, tuple1
and tuple2?
a. common_elements = tuple1.intersection(tuple2)
b. common_elements = tuple1 & tuple2
c. common_elements = tuple1.common(tuple2)
d. common_elements = tuple1.intersection(tuple2)
247. How do you find the product of all elements in a tuple named
numbers?
a. product = multiply(numbers)
b. product = numbers.product()
c. product = 1
d. product = reduce(lambda x, y: x * y, numbers)
Conclusion
In conclusion, the Python Tuples MCQ chapter serves as a comprehensive
and insightful guide to mastering the intricacies of tuples in Python. By
systematically covering fundamental and advanced topics, the chapter
ensures readers understand tuple creation, manipulation, and unique
characteristics. The chapter’s structured approach, combined with real-world
scenarios, solidifies readers’ understanding and equips them with the
expertise to employ tuples effectively in Python programming. Whether for
beginners seeking a solid foundation or experienced developers aiming to
refine their tuple-handling skills, this chapter is a valuable resource for those
navigating the complexities of Python programming. The forthcoming
chapter will provide a complete analysis of MCQs related to Python
Dictionaries.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Within Python programming, dictionaries are highly adaptable and essential
data structures that facilitate storing and retrieving data using key-value pairs.
Dictionaries are considered essential in programming jobs due to their
dynamic nature and rapid lookup method. This Chapter is around the
development of MCQs that are tailored to the topic of Python dictionaries.
The questions provided here are intended to be a great educational tool for
anyone who wants to understand dictionaries in the Python programming
language. This resource benefits learners, educators, and anybody interested
in exploring the intricacies of Python dictionaries. This chapter aims to
enhance the comprehension of dictionary operations, techniques, and
applications. It aims to provide a systematic approach for individuals to test
and reinforce their grasp of key ideas covered in the Python dictionary
chapter.
Objectives
The creation of MCQs with a major focus on the Python dictionary chapter
has many primary goals. These questions provide an all-encompassing
evaluation of the learners’ comprehension of dictionary operations,
methodologies, and applications. The purpose is to provide a comprehensive
examination of the learners’ capability in dealing with dictionaries by
addressing a broad range of topics, such as the building and manipulation of
dictionaries, as well as providing access to and iterating over them. In
addition, they give learners a tool for self-assessment, enabling them to
identify areas of their knowledge that require more study or practice.
3. What happens if you try to access a key that does not exist in a
dictionary using square brackets?
a. It raises a KeyError exception
b. It returns None
c. It adds the key to the dictionary with a default value
d. It returns False
8. Which of the following methods can be used to get a list of all the
values in a dictionary?
a. get()
b. values()
c. items()
d. elements()
9. How can you iterate over both keys and values in a dictionary
using a loop?
a. You cannot iterate over both keys and values simultaneously.
b. Use the items() method
c. Use the keys() method
d. Use a nested loop
12. What is the difference between the get() method and square
bracket notation ([]) when accessing a dictionary?
a. get() returns a default value of the key
b. y is not found, while square brackets raise an error.
c. get() raises an error if the key is not found, while square brackets
return a default value.
d. There is no difference; they both behave the same way.
e. get() and square brackets both raise an error if the key is not
found.
15. How can you remove a key-value pair from a dictionary without
raising an error if the key is not found?
a. Use the remove() method.
b. Use the discard() method.
c. Use the pop() method with a default value.
d. Use the delete() method.
23. What will the keys() method return for an empty dictionary?
a. None
b. An empty list ([])
c. An empty string (“”)
d. It will raise an error.
24. How can you create a dictionary with default values for keys that
do not exist?
a. By using a list comprehension.
b. By using the defaultdict from the collections module.
c. By using the default() method.
d. By using the initialize() method.
25. What does the fromkeys() method do in Python dictionaries?
a. It creates a new dictionary with the same keys and values.
b. It creates a new dictionary with default values for specified keys.
c. It returns the list of keys in the dictionary.
d. It removes all items from the dictionary.
26. How do you change the value associated with a specific key in a
dictionary?
a. Use the set() method.
b. Use the update() method.
c. Use square bracket notation ([]) to reassign the value.
d. Use the modify() method.
33. Which of the following methods can be used to get the value
associated with a key in a dictionary without raising an error if the
key is not found?
a. get_value() c. value()
b. get() d. retrieve()
34. How can you create a dictionary from two lists, one containing
keys and the other containing values?
a. By using the dict() constructor.
b. By using the zip() function.
c. By using a loop to iterate over the lists and add items to the
dictionary.
d. It is not possible to create a dictionary this way.
35. How can you iterate over the keys of a dictionary using a for loop?
a. By using the for key in my_dict: syntax.
b. By using the for key in my_dict.keys(): syntax.
c. By using the for key in my_dict.values(): syntax.
d. It is not possible to iterate over keys using a for loop.
42. Which of the following methods can be used to retrieve a list of all
values in a dictionary?
a. get_values()
b. values()
c. all_values()
d. list_values()
43. How can you change the value associated with a specific key in a
dictionary without using square brackets?
a. Use the set_value() method.
b. Use the update_value() method.
c. Use the modify_value() method.
d. Use the update() method.
44. What is the time complexity for iterating over all keys in a
dictionary using a for loop?
a. O(1) c. O(log n)
b. O(n) d. O(n^2)
45. What will the pop() method return if the key is not found in the
dictionary?
a. None
b. False
c. It will raise a KeyError exception.
d. It will raise a ValueError exception.
47. How can you create a dictionary with default values for keys that
do not exist using a dictionary comprehension?
a. By using a list comprehension
b. By using the defaultdict class
c. By using the setdefault() method
d. It is not possible to create such a dictionary using a
comprehension.
48. Which method can be used to get a list of all the keys in a
dictionary?
a. get_keys() c. all_keys()
b. keys() d. list_keys()
49. What is the time complexity for deleting a key-value pair from a
dictionary using the del statement?
a. O(1) c. O(log n)
b. O(n) d. O(n^2)
50. What is the purpose of the setdefault() method in Python
dictionaries?
a. It sets a default value for a specified key if the key does not exist.
b. It removes a specified key from the dictionary.
c. It updates the value of a specific key.
d. It creates a copy of the dictionary.
53. What is the time complexity for deleting a key-value pair from a
dictionary using the pop() method?
a. O(1) c. O(log n)
b. O(n) d. O(n^2)
54. What is the purpose of the dict() constructor in Python?
a. It creates an empty dictionary.
b. It creates a list of key-value pairs.
c. It converts a list of tuples into a dictionary.
d. It creates a deep copy of an existing dictionary.
55. How do you change the value associated with a specific key in a
dictionary using the update() method?
a. By specifying the new value as an argument to the update()
method.
b. By using square bracket notation ([]) to reassign the value.
c. By calling the update() method with the new value.
d. The update() method cannot be used to change the value of a
specific key.
56. How can you create a dictionary with default values for keys that
do not exist using a normal dictionary (without defaultdict)?
a. By using the default() method.
b. By using the create_default_dict() function.
c. By using a loop to iterate through keys and set default values.
d. It’s not possible to create a dictionary this way.
57. ____ are used to store the values in keys and pairs.
a. Set c. Dictionary
b. Map d. Tuple
58. In the dictionary key and pair which part holds the unique
elements only?
a. Key c. Both
b. Pair d. None of above
59. How do you store dictionary elements?
a. (Dictionaries) c. []
b. {} d. All of above
60. In the dictionary, which symbol is used to separate keys and pairs?
a. , c. :
b. :: d. “”
61. In the dictionary, which symbol is used to separate different
elements?
a. , c. :
b. :: d. “”
62. Which of the following is the correct syntax to create a dictionary?
a. Dict= [ 1:”hi”,2:”hello”]
b. Dict= { 1:”hi”,2:”hello”}
c. Dict= { 1:”hi”,2:”hello”}
d. Dict= [ 1:”hi”,2:”hello”]
74. Which keyword is used to delete/ remove the element from the
dictionary
a. remove() c. del
b. delete() d. remove
75. If you delete the key will the associated pair with the key will be
also get deleted?
a. YES b. NO
76. Select the correct syntax to remove the element from the
dictionary. Suppose you have the following dictionary and you
want to remove the 2nd element.
dict = {1:"include helps",2:"welcomes",3:"you"}
a. del dict [2]
b. del dict=[“2”]
c. del dict(2)
92. Can you include lists and tuples as pairs in the dictionary?
a. Yes b. No
93. Keys of a dictionary must be ______________
a. Antique c. Mutable
b. Unique d. Integers
94. Dictionary in Python are ______________
a. Mutable data type
b. Non-mutable data type
c. Mapping data type
d. Both a and c
123. If we want to store our friends’ mobile numbers with their name,
which data type would be more suitable for us?
a. List c. Tuple
b. String d. Dictionary
124. If we want to store book details including its name and price,
which of the following suitable option?
a. Dictionary c. Tuple
b. List d. String
125. Select the correct statement to merge and store a dictionary D2 in
D1:
a. D1.append(D2)
b. D1.get(D2)
c. D1.update(D2)
d. D1.extend(D2)
127. In the previous question, what code can one write to add50 with
key ‘e’ in dictionary d1.
a. d1.add(‘e’:50) c. d1.e=50
b. d1[‘e’]=50 d. d1.keys(‘e’)=50
128. For the given Dictionary:
d1 ={'a':10,'b';20,'c':30,'d':40}
Which of the following code will display value 30
a. d1[‘c’]
b. d1.get(‘c’)
c. d1.keys(‘c’)
d. both a and b
e. all a, b and c
141. What happens if you try to access a key that does not exist in a
dictionary?
a. It raises a ValueError
b. It returns None
c. It raises a KeyError
d. It returns an empty dictionary
153. What will be the output of the following Python code snippet?
d = {"john":40, "peter":45}
a. “john”, 40, 45, and “peter”
b. “john” and “peter”
c. 40 and 45
d. D = (40:”john”, 45:”peter”)
154. What will be the output of the following Python code snippet?
d = {"john":40, "peter":45} "john" in d
a. True
b. False
c. None
d. Error
157. What will be the output of the following Python code snippet? a=
{1:"A",2:"B",3:"C"} for i,j in a.items():
print(i,j,end=" ")
a. 1 A 2 B 3 C
b. 1 2 3
c. A B C
d. 1:”A” 2:”B” 3:”C”
158. What will be the output of the following Python code snippet? a=
{1:"A",2:"B",3:"C"} print(a.get(1,4))
a. 1
b. A
c. 4
d. Invalid syntax for get method
159. What will be the output of the following Python code snippet? a=
{1:"A",2:"B",3:"C"} print(a.get(5,4))
a. Error, invalid syntax
b. A
c. 5
d. 4
161. What will be the output of the following Python code snippet?
>>> a={1:"A",2:"B",3:"C"} >>> del a
a. Method del does not exist for the dictionary.
b. Del deletes the values in the dictionary.
c. Del deletes the entire dictionary.
d. Del deletes the keys in the dictionary.
163. A copy of the dictionary where the copy of the keys as well as the
values is created for the new dictionary, is called _____ copy.
a. key copy c. deep copy
b. shallow copy d. partial copy
164. Which of the following Python codes will give the same output if
dict = {"diary":1, "book":3, "novel":5}
(i) dict.pop(“book”)
(ii) del dict[“book”]
(iii) dict.update({“diary”:1,”novel”:5})
a. (i), (ii), (iii) c. (i), (iii)
b. (i), (ii) d. (ii), (iii)
165. What will be the output of following Python code ?
d1 = {"a":10, "b":2, "c":3}
str1=""
for i in d1:
str1=strl + str(d1[i]) + " "
str2 = str1[:-1]
print (str2[::-1])
a. 3, 2
b. 3, 2, 10
c. 3, 2, 01
d. Error
168. What will be the output of the following Python coding snippet:
a = {'a':1,'b':2,'c':3}
print (a['a','b'])
a. Key Error
b. [1,2]
c. {‘a’:1,’b’:2}
d. (1,2)
179. Which method can be used to get the value associated with a key,
or a default value if the key is not found?
a. get() c. lookup()
b. fetch() d. find()
180. Which of the following statement creates a dictionary in Python?
a. d = {}
b. d = {40:”john”, 45:”peter”}
c. d = {“john”:40, “peter”:45}
d. All of the mentioned
181. What will be the output of the following Python code snippet:
d = {"john":40, "peter":45}
print(d["john"])
a. 40 c. peter
b. None d. error
182. What will be the output of the following Python code snippet:
d = {"john":40, "peter":45}
print("john" in d)
a. True
b. False
c. Error
183. What will be the output of the following Python code snippet:
d = {"john":40, "peter":45}
d["john"] = 50
print(d["john"]
a. 40 c. peter
b. 50 d. error
184. What will be the output of the following Python code snippet:
d = {"john":40, "peter":45}
del d["john"]
print(d)
a. {“peter”:45}
b. {}
c. Error
185. Which of the following data types can be used as keys in a Python
dictionary?
a. All data types
b. Only immutable data types
c. Only mutable data types
d. None of the above
188. What is the difference between the get() and pop() methods
in Python dictionaries?
a. The get() method returns the value of the specified key if it exists,
otherwise it returns None, while the pop() method removes the
specified key from the dictionary and returns its value.
b. The get() method returns the value of the specified key if it exists,
otherwise it raises a KeyError exception, while the pop() method
removes the specified key from the dictionary and returns its
value.
c. The get() method removes the specified key from the dictionary
and returns its value, while the pop() method returns the value of
the specified key if it exists, otherwise it raises a KeyError
exception.
d. None of the above
189. Which of the following is the correct way to merge two Python
dictionaries?
a. d1.update(d2)
b. d1 + d2
c. d1 = d1 + d2
d. None of the above
190. Which of the following is the correct way to check if a key exists in
a Python dictionary?
a. if key in d:
b. if d.has_key(key)
c. if key in d.keys():
d. All of the mentioned
191. Which of the following is the correct way to sort a Python
dictionary by its keys?
a. d.sort()
b. sorted(d)
c. d.keys().sort()
d. None of the above
194. Which of the following is the correct way to get a list of all the keys
in a Python dictionary?
a. d.keys()
b. d.values()
c. d.items()
d. None of the above
195. Which of the following is the correct way to get a list of all the
values in a Python dictionary?
a. d.keys()
b. d.values()
c. d.items()
d. None of the above
196. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary?
a. d.keys()
b. d.values()
c. d.items()
d. None of the above
198. Which of the following is the correct way to delete a key-value pair
from a Python dictionary?
a. del d[key]
b. d.pop(key)
c. d.remove(key)
d. All of the mentioned
201. Which of the following is the correct way to get the maximum
value in a Python dictionary?
a. max(d.values())
b. min(d.values())
c. d.max()
d. d.min()
202. Which of the following is the correct way to get the minimum
value in a Python dictionary?
a. max(d.values())
b. min(d.values())
c. d.max()
d. d.min()
204. Which of the following is the correct way to get a default value for
a key in a Python dictionary if the key does not exist?
a. d.get(key, default_value)
b. d.setdefault(key, default_value)
c. d.pop(key, default_value)
d. None of the above
207. Which of the following is the correct way to delete a key-value pair
from a dictionary if the key exists?
a. del d[key]
b. d.pop(key)
c. Both (a) and (b)
d. None of the above
208. Which of the following is the correct way to copy a dictionary and
exclude certain keys?
a. {key: value for key, value in d.items() if key not in
exclude_keys}
b. {key: value for key in d.keys() if key not in exclude_keys}
c. {key: value for value in d.values() if key not in exclude_keys}
d. None of the above
209. Which of the following is the correct way to get a list of all the keys
in a Python dictionary that start with a certain letter?
a. d = {key: value for key, value in d.items() if key[0] == “a”}
b. d = {key: value for key in d.keys() if key[0] == “a”}
c. d = {key: value for value in d.values() if key[0] == “a”}
d. None of the above
210. Which of the following is the correct way to get a list of all the
values in a Python dictionary that are greater than a certain
number?
a. d = {key: value for key, value in d.items() if value > 10}
b. d = {key: value for key in d.keys() if value > 10}
c. d = {key: value for value in d.values() if value > 10}
d. None of the above
211. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary where the keys are equal to a
certain value?
a. d = {key: value for key, value in d.items() if key == “a”}
b. d = {key: value for key in d.keys() if key == “a”}
c. d = {key: value for value in d.values() if key == “a”}
d. None of the above
212. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary where the values are equal to a
certain value?
a. d = {key: value for key, value in d.items() if value == 10}
b. d = {key: value for key in d.keys() if value == 10}
c. d = {key: value for value in d.values() if value == 10}
d. None of the above
213. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary where the keys are less than a
certain value and the values are greater than a certain number?
a. d = {key: value for key, value in d.items() if key < 10 and value >
10}
b. d = {key: value for key in d.keys() if key < 10 and value > 10}
c. d = {key: value for value in d.values() if key < 10 and value >
10}
d. None of the above
214. Which of the following is the correct way to get a list of all the
unique values in a Python dictionary?
a. set(d.values())
b. dict.fromkeys(d.values())
c. Both (a) and (b)
d. None of the above
216. Which of the following is the correct way to check if a value exists
in a Python dictionary?
a. value in d
b. d.contains(value)
c. d.has_value(value)
d. None of the above
217. Which of the following is the correct way to get a list of all the keys
in a Python dictionary that are not present in another dictionary?
a. set(d1) - set(d2)
b. set(d2) - set(d1)
c. Both (a) and (b)
d. None of the above
218. Which of the following is the correct way to get a list of all the
values in a Python dictionary that are not present in another
dictionary?
a. set(d1.values()) - set(d2.values())
b. set(d2.values()) - set(d1.values())
c. Both (a) and (b)
d. None of the above
219. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary that are not present in another
dictionary?
a. set(d1.items()) - set(d2.items())
b. set(d2.items()) - set(d1.items())
c. Both (a) and (b)
d. None of the above
221. Which of the following is the correct way to shallow copy a Python
dictionary?
a. d1 = d2
b. d1 = d2.copy()
c. d1 = dict(d2)
d. All of the mentioned
222. Which of the following is the correct way to deep copy a Python
dictionary?
a. d1 = d2.copy()
b. d1 = copy.deepcopy(d2)
c. d1 = dict(d2)
d. None of the above
230. Which of the following is the correct way to get the number of key-
value pairs in a dictionary?
a. len(d) (
b. d.size()
c. d.count() (
d. None of the above
233. Which of the following is the correct way to get a list of all the keys
in a dictionary that start with a certain letter, sorted in ascending
order?
a. sorted([key for key in d.keys() if key[0] == “a”])
b. sorted(d.keys(), key=lambda x: x[0])
c. Both (a) and (b)
d. None of the above
234. Which of the following is the correct way to get a list of all the
values in a Python dictionary that are greater than a certain
number, sorted in descending order?
a. sorted([value for value in d.values() if value > 10], reverse=True)
b. sorted(d.values(), key=lambda x: x, reverse=True)
c. Both (a) and (b)
d. None of the above
235. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary where the keys are equal to a
certain value, sorted by the values in ascending order?
a. sorted([(key, value) for key, value in d.items() if key == “a”],
key=lambda x: x[1])
b. sorted(d.items(), key=lambda x: x[0])
c. Both (a) and (b)
d. None of the above
236. Which of the following is the correct way to get a list of all the key-
value pairs in a Python dictionary where the values are greater
than a certain number, sorted by the keys in descending order?
a. sorted([(key, value) for key, value in d.items() if value > 10],
key=lambda x: x[0], reverse=True)
b. sorted(d.items(), key=lambda x: x[1], reverse=True)
c. Both (a) and (b)
d. None of the above
240. Which of the following methods can be used to merge two Python
dictionaries?
a. update()
b. merge()
c. combine()
d. None of the above
241. Which of the following is the most efficient way to check if a value
exists in a Python dictionary?
a. Looping through the dictionary and checking each value
individually.
b. Using the in operator.
c. Using the values() method.
d. Using the items() method.
242. Which of the following is the best way to create a dictionary from
a list of key-value pairs?
a. Using a for loop.
b. Using a comprehension.
c. Using the dict() constructor.
d. Using the fromkeys() method.
243. Which of the following is the best way to sort a Python dictionary
by its keys?
a. Using the sort() method.
b. Using the sorted() function.
c. Using the keys() method.
d. None of the above
Conclusion
These multiple-choice questions are a powerful and comprehensive tool,
allowing students to test, reinforce, and broaden their comprehension of
Python dictionaries, a key data structure in the language. These questions
encourage analytical thinking and problem-solving abilities, thus
strengthening the ability to apply solutions based on the lexicon. They do this
by addressing many theoretical topics and real-world events. They offer a
method for conducting one’s evaluation and keeping track of the progress,
both of which contribute to a more profound understanding of fundamental
programming ideas. The next chapter will provide a complete analysis of
MCQs related to file handling in Python.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Python is a programming language that is both flexible and extensively
utilized. It is at the heart of a wide variety of applications, including web
development and data analysis, to name just a few. File handling is one of its
core features, and because it enables developers to interact with data kept in
files, it is an essential element of the skill set required of any Python
programmer. Due to Python’s ever-increasing popularity, there is an ever-
increasing demand for high-quality instructional resources that may assist
students in mastering the fundamentals of the programming language. File
handling is the process of interacting with files in Python, which may be used
for various reasons, including reading, writing, generating, and altering data
saved in files on the computer’s file system. File handling is sometimes
referred to as working with files. You can interact with files and durably save
data using Python since it has built-in methods and modules that handle file
operations.
Objectives
This chapter aims to give students access to a helpful resource that can be
used for self-evaluation and to improve their grasp on this crucial subject
matter. Even though abundant information is available in the form of
tutorials, books, and online resources, adding MCQs provides a one-of-a-kind
opportunity to hone one’s comprehension and evaluate one’s level of
expertise. In the end, those individuals pursuing self-paced learning, as well
as instructors, will profit from the availability of these meticulously written
MCQs. People interested in mastering Python’s file-handling skills will find
that these questions are a helpful resource and an essential step toward
becoming skilled Python programmers. With the help of this chapter, we
hope to make it easier for learners to acquire fundamental capabilities in
Python’s file handling, enabling them on their path toward programming
greatness.
12. Which mode is used to open a file for reading and writing but
creates the file if it does not exist?
a. “r” c. “a”
b. “w” d. “w+”
13. How do you check if a file exists without opening it in Python?
a. Use the os.exists(file) function.
b. Use the file.exists() method.
c. Use the os.path.exists(file) function.
d. Use the file.exist() method.
14. What method can be used to read the entire contents of a file into
a string?
a. read() c. readall()
b. readlines() d. readline()
15. When using the open() function to open a file, what is the default
mode if you do not specify it?
a. “r” c. “a”
b. “w” d. “x”
16. How do you write a newline character to a file in Python?
a. Using the \n escape sequence.
b. Using the newline() function.
c. Using the n character.
d. Using the \\n escape sequence.
17. What function can be used to check the current position within a
file?
a. fileposition()
b. tell()
c. currentpos()
d. position()
18. Which method can be used to remove a file from the file system in
Python?
a. remove() c. erase()
b. delete() d. destroy()
19. What is the purpose of the seek() method in file handling?
a. It is used to create a new file.
b. It moves the file pointer to a specific position within the file.
c. It is used to close a file.
d. It writes data to a file.
23. How can you iterate through each line in a file using a for loop in
Python?
a. Use the for line in file: syntax.
b. Use the for line in file.read(): syntax.
c. Use the for line in file.readlines(): syntax.
d. Use the for line in file.readline(): syntax.
28. To read the first three lines of a file into a list in Python, which
method is commonly used?
a. readlines()[:3] c. readlines(3)
b. readline(3) d. readline()[:3]
29. How can you check if a file is at its end in Python?
a. Use the file.at_end() method.
b. Use the file.end() method.
c. Check if file.read() returns an empty string.
d. Use the file.eof() method.
30. Which method moves the file pointer to the beginning of the file in
Python?
a. reset() c. move(0)
b. seek(0) d. position(0)
31. What is the purpose of the os module in Python for file handling?
a. It allows you to create and open files.
b. It provides functions for working with file paths and directories.
c. It is used for reading and writing files.
d. It handles file compression and decompression.
34. Which of the following statements is true about text mode (‘t’) and
binary mode (‘b’) when opening a file in Python?
a. ‘t’ mode is for reading text files, and ‘b’ mode is for binary files.
b. ‘t’ mode is for reading binary files, and ‘b’ mode is for text files.
c. Both ‘t’ and ‘b’ modes are used interchangeably for all file types.
d. There is no difference between ‘t’ and ‘b’ modes in Python.
42. Which method is used to change the current position of the file
pointer in Python?
a. position()
b. set_position()
c. move_to()
d. seek()
43. In Python, what is the purpose of the os.path.exists()
function?
a. It checks if a file exists.
b. It creates a new file.
c. It opens a file for reading.
d. It deletes a file.
45. How can you list the files and directories in a directory using
Python?
a. Use the listdir() method from the os module.
b. Use the files_and_directories() function.
c. Use the ls() method.
d. Use the os.listdir() function.
55. How can you open a file in Python for both reading and writing
while creating the file if it does not exist?
a. “r” c. “a”
b. “w” d. “a+”
56. What does the os.path.isdir() function returns if the given
path is not a directory?
a. True c. None
b. False d. An error message
57. In Python, what is the purpose of the os.path.realpath()
function?
a. Checks if a path is absolute or relative.
b. Returns the absolute path of a specified file.
c. Converts a relative path to an absolute path.
d. Returns the canonical path of a specified file.
66. How can you open a file for writing in Python, creating it if it
doesn’t exist, and overwriting its contents?
a. “r” c. “a”
b. “w” d. “x”
67. What does the write() method return after successfully writing
data to a file in Python?
a. The number of bytes written.
b. The content of the file.
c. The file’s size.
d. None
70. When writing data to a file in Python, what does the “a” mode do?
a. Appends data to the end of the file.
b. Reads data from the file.
c. Overwrites the file.
d. Creates a new file.
71. How can you write multiple lines to a file using the
writelines() method in Python?
a. Use a loop to call write() for each line.
b. Provide a list of lines to the writelines() method.
c. Use the writelinen() function.
d. Use the writemultiple() method.
73. How can you read a specific number of characters from a file in
Python?
a. Use the readline(n) method
b. Use the read(n) method
c. Use the readlines(n) method
d. Use the readto(n) method
76. How can you read all lines from a file into a list in Python?
a. Use the readline() method in a loop.
b. Use the readlines() method.
c. Use the readall() method.
d. Use the readline(n) method.
77. What is the purpose of the seek() method in file handling?
a. It is used to create a new file.
b. It moves the file pointer to a specific position within the file.
c. It is used to close a file.
d. It writes data to a file.
78. How can you read all lines from a file and store them in a list in
Python?
a. Use the read() method.
b. Use the readline() method in a loop.
c. Use the readall() method.
d. Use the readlines() method.
79. What does the tell() method return when used with a file in
Python?
a. The size of the file.
b. The current position within the file.
c. The number of lines in the file.
d. The file’s modification time.
80. When you open a file for writing in Python using the “w” mode,
what happens to the existing content of the file?
a. It is preserved.
b. It is appended to.
c. It is overwritten with new data.
d. It is read and returned.
85. What does the truncate() method do in Python when used with
a file in write mode?
a. Deletes the file
b. Resizes the file to the specified size
c. Appends data to the end of the file
d. Reads the entire file
86. How do you read a binary file in Python using the open()
function?
a. Use the “rb” mode when opening the file
b. Use the “r” mode when opening the file
c. Use the “wb” mode when opening the file
d. Use the “b” mode when opening the file
87. What method is used to read the next line from a file in Python?
a. readline()
b. read()
c. readlines()
d. nextline()
88. When using the open() function in Python, what does the “x”
mode do when opening a file?
a. Opens the file in binary mode
b. Creates a new file if it doesn’t exist; otherwise, it fails
c. Appends data to the end of the file
d. Opens the file in write mode
89. How can you read the entire content of a file into a single string in
Python?
a. Use the read() method
b. Use the readlines() method
c. Use the readline() method in a loop
d. Use the readall() method
93. When opening a file in Python using the “a” mode, what happens
if the file does not exist?
a. An error is raised
b. The file is created
c. The file is opened in read mode
d. The program terminates
94. How can you write data to a file in Python so that it does not
overwrite the existing content but appends to it?
a. Use the “r+” mode when opening the file
b. Use the write() method with the “a” mode
c. Use the “a+” mode when opening the file
d. Use the append() method
95. What is the purpose of the tell() method when used with a file
in Python?
a. It returns the total number of lines in the file
b. It returns the file’s size in bytes
c. It returns the current position within the file
d. It returns the file’s modification time
96. How can you read a specific line from a file in Python?
a. Use the readline() method with an index as an argument
b. Use the readlines() method with a line number as an argument
c. Use the readline(n) method with the line number as an argument
d. Use the readline() method in a loop
97. When using the open() function to open a file, what does the
“rb” mode do?
a. Opens the file in binary mode for reading
b. Opens the file in binary mode for writing
c. Reads the file as binary data
d. Reads the file as text data
98. How do you read a specific number of lines from a file in Python?
a. Use the readline() method with a count as an argument.
b. Use the readlines() method in a loop with a count.
c. Use the readline(n) method with a count as an argument.
d. Count the lines using the readline() method in a loop.
99. What does the flush() method do in Python when used with a
file?
a. Closes the file.
b. Writes the file contents to disk.
c. Clears the file content.
d. Reads the file content.
100. How can you check if a file exists before reading or writing to it in
Python?
a. Use the os.file_exists() function.
b. Use the os.path.exists() function.
c. Use the file.exists() method.
d. Use the file.check_exists() method.
101. When reading from a file in Python using the open() function,
what is the default reading mode if you do not specify a mode?
a. “r+” c. “a”
b. “w” d. “r”
102. What method is used to write data to a file in Python?
a. read() c. writedata()
b. readline() d. write()
103. How can you read all lines from a file into a list in Python while
preserving newline characters?
a. Use the read() method
b. Use the readline() method in a loop
c. Use the readlines() method
d. Use the readall() method
104. What is the default file position when you open a file in read mode
in Python?
a. Beginning of the file (position 0)
b. End of the file
c. Middle of the file
d. It varies depending on the file’s content
105. How do you change the file position to the end of the file in
Python?
a. Use the file.seek(0) method
b. Use the file.seek(1) method
c. Use the file.seek(0, 2) method
d. Use the file.end() method
106. What method moves the file position to a specified byte in Python?
a. move() c. seek()
b. position() d. shift()
107. When you open a file in write mode in Python, what is the initial
file position?
a. Beginning of the file (position 0)
b. End of the file
c. Middle of the file
d. It varies depending on the file’s content
108. What does the seek() method return after moving the file
position successfully in Python?
a. The new file position
b. The file’s size
c. The content of the file
d. None
109. In Python, how do you move the file position to the beginning of
the file?
a. Use the file.seek(0) method.
b. Use the file.seek(1) method.
c. Use the file.seek(0, 2) method.
d. Use the file.begin() method.
110. When using the tell() method to get the file position, what does
it return?
a. The file’s size
b. The new line number
c. The current position within the file
d. The file’s modification time
111. How can you move the file position to a specified line number in a
text file in Python?
a. Use the file.line(number) method
b. Use the file.seek(0) method
c. Use the file.seek() method with an offset
d. Use the file.position() method
112. In Python, what does the tell() method return if the file
position is at the beginning of the file?
a. 0 c. -1
b. 1 d. None
113. How can you move the file position to the end of the file in Python?
a. Use the file.seek(0) method
b. Use the file.seek(1) method
c. Use the file.seek(0, 2) method
d. Use the file.end() method
114. How can you move the file position to the middle of the file in
Python?
a. Use the file.middle() method.
b. Use the file.seek(0.5) method.
c. Use the file.seek(0.5, 1) method.
d. Use the file.center() method.
115. What does the seek() method do in Python when used with a file
in write mode?
a. Closes the file
b. Moves the file position to the specified location
c. Writes data to the file
d. Reads data from the file
116. When using the tell() method to get the file position, what is
the returned value if the file position is at the end of the file?
a. 0 c. -1
b. 1 d. None
117. In Python, how do you move the file position to the middle of the
file?
a. Use the file.middle() method
b. Use the file.seek(0.5) method
c. Use the file.seek(0.5, 1) method
d. Use the file.center() method
118. What does the seek() method return when it fails to move the
file position in Python?
a. The new file position
b. False
c. None
d. An error message
119. How can you move the file position to a specific byte in a binary
file in Python?
a. Use the file.byte() method
b. Use the file.seek(0, byte) method
c. Use the file.seek(byte) method
d. Use the file.position(byte) method
120. When opening a file in read mode in Python, what is the default
file position?
a. End of the file
b. Middle of the file
c. Beginning of the file (position 0)
d. Random position
121. How do you move the file position to a specific character in a text
file in Python?
a. Use the file.character() method
b. Use the file.seek(0, character) method
c. Use the file.seek(character) method
d. Use the file.position(character) method
124. What is the purpose of the seek() method when used with a file
in Python?
a. It moves the file position to the end of the file
b. It closes the file
c. It writes data to the file
d. It moves the file position to a specified location
125. When using the tell() method to get the file position, what does
it return when the file is closed?
a. 0 c. -1
b. 1 d. None
126. How do you move the file position to the beginning of the file in
Python?
a. Use the file.seek(0) method
b. Use the file.seek(1) method
c. Use the file.seek(0, 2) method
d. Use the file.begin() method
127. How can you move the file position to a specific line number in a
text file in Python?
a. Use the file.line() method
b. Use the file.seek(0, line) method
c. Use the file.seek(line) method
d. Use the file.position(line) method
128. In Python, what does the seek() method return when it fails to
move the file position?
a. The new file position
b. False
c. None
d. An error message
129. How do you move the file position to the end of the file in Python?
a. Use the file.seek(0) method.
b. Use the file.seek(1) method.
c. Use the file.seek(0, 2) method.
d. Use the file.end() method.
130. When using the tell() method to get the file position, what is
the returned value if the file is closed?
a. 0 c. -1
b. 1 d. None
131. Which module in Python is commonly used for renaming and
deleting files?
a. os c. sys
b. shutil d. pathlib
132. How can you rename a file in Python using the shutil module?
a. shutil.rename(“old_file.txt”, “new_file.txt”)
b. shutil.move(“old_file.txt”, “new_file.txt”)
c. shutil.copy(“old_file.txt”, “new_file.txt”)
d. shutil.rename_file(“old_file.txt”, “new_file.txt”)
133. Which function from the shutil module is used to rename a file
in Python?
a. move() c. copy()
b. rename() d. replace()
134. How can you delete a file in Python using the os module?
a. os.remove(“file.txt”)
b. os.delete(“file.txt”)
c. os.delete_file(“file.txt”)
d. os.delete(“file.txt”)
135. What will happen if you try to delete a non-existent file using
os.remove in Python?
a. It will raise an error
b. It will create an empty file
c. It will delete all files in the directory
d. It will prompt you for confirmation
137. How can you check if a file exists before deleting it in Python using
the os module?
a. os.file_exists(“file.txt”)
b. os.exists_file(“file.txt”)
c. os.path.exists(“file.txt”)
d. os.isfile(“file.txt”)
139. How can you delete a directory and its contents in Python using
the shutil module?
a. shutil.rmdir(“directory”)
b. shutil.remove(“directory”)
c. shutil.rmtree(“directory”)
d. shutil.delete(“directory”)
141. Which module in Python is used for working with file and
directory paths?
a. os c. sys
b. shutil d. pathlib
142. How can you delete an empty directory in Python using the os
module?
a. os.remove(“directory”)
b. os.rmdir(“directory”)
c. os.delete(“directory”)
d. os.delete_directory(“directory”)
146. How can you delete a directory and its contents in Python using
the os module?
a. os.rmdir(“directory”)
b. os.remove(“directory”)
c. os.rmtree(“directory”)
d. os.delete(“directory”)
148. How can you check if a file or directory exists in Python using the
pathlib module?
a. pathlib.is_file(“file.txt”)
b. pathlib.exists(“file.txt”)
c. pathlib.file_exists(“file.txt”)
d. pathlib.is_dir(“directory”)
150. How can you delete a directory and its contents in Python using
the pathlib module?
a. pathlib.remove(“directory”)
b. pathlib.rmtree(“directory”)
c. pathlib.delete(“directory”)
d. pathlib.delete_tree(“directory”)
151. How can you delete an empty directory in Python using the
pathlib module?
a. pathlib.rmdir(“directory”)
b. pathlib.remove(“directory”)
c. pathlib.delete(“directory”)
d. pathlib.delete_directory(“directory”)
152. How can you check if a file or directory exists in Python using the
os.path module?
a. os.path.isfile(“file.txt”)
b. os.path.exists(“file.txt”)
c. os.path.is_file(“file.txt”)
d. os.path.is_dir(“directory”)
155. When you use the seek() function to move the file position,
what is the default reference point for seeking in Python?
a. Beginning of the file
b. Middle of the file
c. Current file position
d. End of the file
156. How can you move the file position to the end of the file using the
seek() function in Python?
a. file.seek(0) c. file.seek(0, 2)
b. file.seek(1) d. file.seek(2)
157. What is the purpose of the tell() function when used with a file
in Python?
a. It tells you the current line number
b. It tells you the size of the file
c. It tells you the current file position
d. It tells you the file’s encoding
158. What is the purpose of the seek() function when used with a file
in Python?
a. It moves the file position to the end of the file
b. It closes the file
c. It writes data to the file
d. It moves the file position to a specified location
159. What returns when the file is closed when using the tell()
function to get the file position?
a. 0 c. -1
b. 1 d. None
160. In Python, what does the seek() function return when it fails to
move the file position?
a. The new file position
b. False
c. None
d. An error message
161. What does the seek() function do in Python when used with a
file in write mode?
a. Closes the file
b. Moves the file position to the specified location
c. Writes data to the file
d. Reads data from the file
163. How can you open a binary file in Python for reading?
a. file = open(“file.txt”, “rb”)
b. file = open(“file.txt”, “r”)
c. file = open(“file.txt”, “wb”)
d. file = open(“file.txt”, “w”)
165. What is the difference between reading a binary file and a text file
in Python?
a. There is no difference
b. Binary files can only be read using open(), while text files can be
read using read()
c. Reading binary files requires specifying “rb” as the mode, while
text files require “rt”
d. Binary files can only be read using read(), while text files can be
read using readline()
167. What is the difference between writing to a binary file and a text
file in Python?
a. There is no difference
b. Writing to a binary file requires specifying “rb” as the mode,
while text files require “rt”
c. Binary files can only be written using read(), while text files can
be written using write()
d. Writing to a binary file requires specifying “wb” as the mode,
while text files require “wt”
170. What is the purpose of the seek() function when working with
binary files in Python?
a. To close the file
b. To read the file from the beginning
c. To move the file position to a specific location
d. To print the file contents
171. How can you write binary data to a file using the write()
method in Python?
a. file.write(“data”)
b. file.write(b”data”)
c. file.write_bytes(“data”)
d. file.write_binary(“data”)
174. What is the purpose of the close() method when working with
binary files in Python?
a. To read the file
b. To write data to the file
c. To move the file position
d. To release system resources and close the file
176. What attribute of a file object is used to retrieve the file’s name in
Python?
a. filename c. file_name
b. name d. file
177. What attribute of a file object is used to determine if the file is
closed in Python?
a. is_closed c. isopen
b. closed d. close_status
178. How can you retrieve the file mode (e.g., ‘r’, ‘w’, ‘a’) from a file
object in Python?
a. file.mode c. file.get_mode()
b. file.mode() d. file.open_mode()
179. What attribute of a file object returns the file’s current position in
Python?
a. position c. file_position
b. current_position d. tell()
180. What is the purpose of the closed attribute of a file object in
Python?
a. To close the file
b. To store the file’s content
c. To check if the file is closed
d. To retrieve the file’s name
181. How can you retrieve the name of a file from a file object in
Python?
a. file.filename c. file.get_name()
b. file.name d. file.file_name()
182. What is the purpose of the name attribute of a file object in
Python?
a. To store the file’s content
b. To retrieve the file’s size
c. To determine if the file is closed
d. To return the file’s name
183. How can you check if a file is closed using its closed attribute in
Python?
a. file.closed()
b. file.isclosed
c. file.is_closed()
d. file.closed
184. What is the purpose of using command line arguments in file
handling with Python?
a. To specify the file path in the code
b. To execute shell commands
c. To define environment variables
d. To close the file
185. When executing a Python script, how can you pass a file path as a
command line argument?
a. By enclosing the file path in quotes
b. By using python script.py --file path/to/file.txt
c. Adding the file path after the script name, e.g., python script.py
path/to/file.txt
d. By setting an environment variable for the file path
187. How can you retrieve the file path passed as a command line
argument using argparse?
a. argparse.get_arguments()
b. argparse.arguments
c. argparse.parse_args()
d. argparse.args
188. What does the argparse.ArgumentParser class do in
Python?
a. Closes files
b. Parses command line arguments
c. Defines variables
d. Executes shell commands
191. How can you access the file path passed as a command line
argument using argparse in Python?
a. args.file_path
b. argparse.get_argument(“file_path”)
c. argparse.get_args(“file_path”)
d. args.get(“file_path”)
192. _________ removes the given character from trailing end or from
the right end.
a. strip()
b. rstrip()
c. lstrip()
d. None of the above
196. In Python, which module reads and writes data in a binary format
using pickling and unpickling?
a. json c. pickle
b. gzip d. fileinput
197. What is the purpose of the pickle.dump() function in Python?
a. To compress data
b. To read a text file
c. To serialize and save Python objects to a file
d. To list all files in a directory
200. How does the fileinput module allow you to read lines from
multiple input streams in Python?
a. By using fileinput.readlines()
b. By specifying the file paths as arguments
c. By using a single input source
d. By using fileinput.read_input()
202. Which function is used to compress a file using the gzip module
in Python?
a. gzip.compress()
b. gzip.deflate()
c. gzip.compress_file()
d. gzip.GzipFile()
203. How do you open a file for reading with gzip in Python?
a. gzip.open(“file.txt”, “rb”)
b. gzip.read(“file.txt”)
c. gzip.read_file(“file.txt”)
d. gzip.decompress(“file.txt”)
205. How do you open a file for reading with bz2 in Python?
a. bz2.read_file(“file.txt”)
b. bz2.decompress(“file.txt”)
c. bz2.open(“file.txt”, “rb”)
d. bz2.compress_file(“file.txt”)
206. What is the primary purpose of the shelve module in Python?
a. To work with JSON data
b. To create compressed files
c. To serialize and deserialize Python objects
d. To compress and decompress files
207. How do you open a shelve file for read and write access in Python?
a. shelve.open(“file.db”, “rw”)
b. shelve.open(“file.db”, “rb”)
c. shelve.open(“file.db”, “wb”)
d. shelve.open(“file.db”, “rw”)
216. Which function is used to search for files and directories in Python
using the fnmatch module?
a. fnmatch.match() c. fnmatch.find()
b. fnmatch.search() d. fnmatch.filter()
217. What is the primary purpose of the os.path.exists()
function in Python?
a. To create a file
b. To check if a path exists
c. To get the size of a file
d. To check if a path is a directory
220. What advantage does file handling provide for data persistence in
Python?
a. Increased volatility of data
b. Decreased data security
c. Long-term storage and retrieval of data
d. Reduced data integrity
221. What is one disadvantage of using files for data storage in Python?
a. Improved data integrity
b. Difficulty in data sharing and synchronization
c. Real-time data processing
d. Enhanced data security
224. What is one advantage of using files for storing configuration data
in Python applications?
a. Real-time configuration updates
b. Improved data security
c. Data persistence across application runs
d. Reduced data retrieval speed
226. In Python, how does file handling benefit applications that require
data logging?
a. By increasing data corruption
b. By ensuring real-time data retrieval
c. By allowing data to be written to log files
d. By reducing data persistence
227. What is the potential disadvantage of using files for data storage in
Python compared to databases?
a. Better data organization
b. Improved data retrieval speed
c. Limited support for concurrent access
d. Enhanced data security
229. What is one disadvantage of using file handling in Python for real-
time data processing?
a. Improved data integrity
b. Increased I/O overhead
c. Better data organization
d. Reduced data persistence
230. What is the advantage of using files for data storage in Python
compared to a database?
a. Faster data retrieval
b. Improved data security
c. No need for a database management system
d. Better support for complex queries
233. What is the disadvantage of using files for data storage in Python
compared to a database?
a. Improved data organization
b. Increased complexity of data retrieval
c. Enhanced data security
d. Better support for data integrity constraints
237. What is the disadvantage of using files for data storage in Python
compared to using an in-memory data structure?
a. Better data organization
b. Limited data retention
c. Enhanced data retrieval speed
d. Improved data sharing
247. Which Python file object method is used to read the entire content
of a file into a string?
a. readlines() c. read()
b. readline() d. write()
248. What does a file object’s write() method do in Python?
a. Reads the file content
b. Closes the file
c. Writes data to the file
d. Appends data to the end of the file
Conclusion
In conclusion, developing Python File Handling MCQs is essential to the
overall landscape of Python programming education. These multiple-choice
questions give the student more agency, advance comprehension, and offer a
dynamic approach to connecting with the topic. This resource serves a crucial
function in ensuring that individuals have the tools they need to flourish in
the profession. This plays an increasingly important role as Python’s
influence in the programming world continues to climb.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
In the world of Python programming, uncommon circumstances or errors are
unavoidable; it is essential for solid code to handle these instances
effectively. The system for managing exceptions built into the Python
programming language offers a strong way to manage and respond to
unexpected occurrences that interfere with the typical operation of a program.
The multiple-choice questions in this chapter are centered on Python’s
approach to managing exceptions. The purpose of these multiple-choice
questions is to act as a valuable educational resource for students, teachers,
and anybody interested in fully grasping how to handle exceptions in Python
efficiently. The purpose of this section is to cover various aspects of Python’s
exception handling. These aspects include the try-except block, raising
exceptions, handling specific error types, and utilizing exceptional handling
best practices. This section offers a structured means for self-assessment and
reinforcing essential concepts in Python’s exception-handling chapter.
Objectives
The key goals of developing MCQs for this chapter is to provide questions
that cover a wide range of topics and to be as exhaustive as possible. These
multiple-choice questions aim to determine how well learners can handle
exceptions in Python. The purpose of these questions is to provide a resource
that is valuable, interesting, and instructive, to accommodate a variety of
learning styles, and to improve understanding of Python’s mechanisms for
managing exceptions.
12. What type of exceptions are caught by the except block without
specifying a particular exception type in Python?
a. All exceptions c. NameError
b. SyntaxError d. ValueError
13. Which of the following keywords is used to define a custom
exception in Python?
a. raise c. exception
b. create d. def
14. What is the primary purpose of using multiple except blocks in
Python?
a. To handle only a specific type of exception.
b. To handle multiple exceptions at once.
c. To handle every possible exception.
d. To ignore exceptions.
18. Which method is used to display the error message associated with
an exception in Python?
a. print_error()
b. message()
c. str()
d. __str__()
39. What is the significance of using separate except blocks for distinct
exceptions in Python?
a. It decreases code readability.
b. It increases performance.
c. It makes the code less maintainable.
d. It allows for specific handling of different exceptions.
43. How are exceptions handled when using multiple except blocks
in Python?
a. In a specific order defined by the programmer.
b. Randomly selected.
c. In the order they are defined in the code.
d. In reverse order.
53. What is the primary advantage of using specific except blocks for
distinct exceptions in Python?
a. It improves performance.
b. It simplifies the code structure.
c. It allows for handling different exceptions differently.
d. It reduces the chances of encountering exceptions.
55. How does the except block handle exceptions when no specific
exception type is mentioned in Python?
a. It catches only syntax errors.
b. It catches all exceptions that occur in the try block.
c. It doesn’t catch any exceptions.
d. It catches only predefined exceptions.
58. How are multiple exceptions handled within a single except block
in Python?
a. Each exception type should be separated by a comma
b. Using a wildcard (*) to catch any exception
c. Creating separate except blocks for each exception
d. By specifying all exception types within parentheses
62. How does Python manage the order of exception handling when
utilizing multiple exceptions within a single except block?
a. Exceptions are handled randomly
b. Exceptions are handled in the order they are listed
c. Exceptions are handled in reverse order
d. Exceptions are handled simultaneously
64. How does the ordering of exceptions affect the exception handling
process when using multiple exceptions in a single except block
in Python?
a. It has no impact on the handling of exceptions
b. The last exception type has the highest priority
c. The first exception type has the highest priority
d. It leads to an ambiguity error
65. What is the advantage of using a single except block for multiple
exceptions in Python?
a. Reducing code complexity
b. Avoiding ambiguity in exception handling
c. Improving error traceability
d. Handling exceptions based on a defined hierarchy
66. How does Python interpret the order of exception types within a
multiple except block?
a. The last exception type has higher precedence
b. Exceptions are processed in random order
c. Exceptions are handled in the order they are defined
d. The first exception type has higher precedence
68. How does Python handle exceptions if multiple exception types are
mentioned in a single except block?
a. Exceptions are handled randomly
b. Only the last exception type is handled
c. The first matching exception is handled
d. All matching exceptions are handled
71. In Python, how does using a single except block for multiple
exceptions affect the code structure?
a. Reduces code flexibility
b. Increases code readability
c. Makes code maintenance complex
d. Enhances exception traceability
72. What is the primary advantage of using a single except block for
handling multiple exceptions in Python?
a. Allows handling different exceptions differently
b. Reduces code verbosity
c. Simplifies exception hierarchy
d. Enhances error traceability
74. What is the primary advantage of using a single except block for
multiple exceptions in Python?
a. Offers precise exception handling for each type
b. Simplifies the code and avoids repetition
c. Increases code complexity
d. Provides better code performance
78. How does the presence of an else block affect the flow of code
execution in Python’s exception handling?
a. It modifies the behavior of the try block
b. It alters the control flow when an exception occurs
c. It introduces an error if exceptions are raised
d. It changes the code behavior when no exceptions are raised
80. In Python, when is the else block executed in relation to the try
block?
a. It is executed before the try block
b. It executes after the try block only if an exception occurs
c. It executes before the except block
d. It executes after the try block if no exceptions occur
82. In Python, how does the presence of the else block affect the
code when exceptions are raised?
a. It executes before the except block
b. It doesn’t affect the handling of exceptions
c. It always leads to an unhandled exception
d. It does not execute if an exception is raised
84. What happens if an exception is raised and not handled within the
try block with an associated else clause in Python?
a. The else block is executed
b. It results in an unhandled exception
c. The except block handles the unhandled exception
d. The code produces a syntax error
99. In Python, how does the raise statement impact the program
flow?
a. It doesn’t impact program flow
b. It halts the program immediately
c. It continues to the finally block
d. It alters the flow by raising specified exceptions
100. What is the primary objective of raising exceptions in Python?
a. To bypass the error handling mechanism
b. To handle errors and recover
c. To interrupt the program execution
d. To signify and handle errors
105. How does the raise statement affect program flow in Python?
a. It allows skipping the except block
b. It doesn’t affect the program flow
c. It alters the flow by initiating specified exceptions
d. It proceeds to the finally block immediately
113. In Python, what is the role of the try block within a function?
a. To define the function’s logic
b. To execute specific instructions
c. To handle exceptions that may occur during function execution
d. Functions cannot contain try blocks
114. How does error handling within functions contribute to the code
structure in Python?
a. It causes syntax errors within the function
b. It simplifies the code by consolidating error management
c. It increases complexity by adding more lines of code
d. Error handling doesn’t impact code structure
124. What is the standard base class for all built-in exceptions in
Python?
a. BaseException c. GeneralError
b. RootException d. BasicError
125. Which built-in exception in Python is raised when a key is not
found in a dictionary?
a. KeyError
b. ValueError
c. NotFoundException
d. IndexError
132. What is the specific built-in exception raised when a module, class,
or function is requested but not found?
a. ModuleNotFoundError
b. ObjectNotFoundError
c. ResourceNotFoundError
d. MissingElementError
133. Which built-in exception in Python is raised when an object is not
hashable?
a. HashError
b. UnhashableError
c. NotHashableError
d. TypeError
134. What is the specific built-in exception raised when a value is too
large for a specific data type?
a. SizeError c. LargeValueError
b. OverflowError d. CapacityError
135. Which built-in exception in Python is raised when an
inappropriate argument is passed to a function?
a. ImproperArgumentError
b. InvalidArgumentError
c. TypeError
d. ArgumentError
136. What is the specific built-in exception raised when the format
string or the number of arguments does not coincide?
a. MismatchError c. ValueError
b. FormatError d. TypeError
137. Which built-in exception is raised when an invalid format is
detected in a string or any operation?
a. InvalidFormatError
b. FormatError
c. InvalidOperationError
d. StringFormatError
138. What is the specific built-in exception raised when the user
attempts to access a file or directory that does not exist?
a. AccessError
b. NonexistentError
c. FileNotFoundError
d. DirectoryError
194. Which of the following scenarios is an appropriate use case for the
finally block?
a. To exclusively handle exceptions raised in the try block
b. To ignore the exceptions and halt program execution
c. To execute cleanup code, whether an exception occurs or not
d. To raise multiple exceptions within a single try block
195. What is the key advantage of using the finally block in Python?
a. It suppresses all exceptions raised in the try block
b. It is not mandatory and can be omitted
c. It executes cleanup code under all circumstances
d. It terminates the program’s execution instantly
196. In Python, which of the following blocks is always executed,
regardless of an exception occurring in the try block?
a. catch block
b. finally block
c. except block
d. else block
201. How does the finally block affect the flow of control in
Python’s exception handling?
a. It diverts the control to the catch block
b. It completely halts the code execution
c. It ensures the execution of specific cleanup code
d. It automatically ignores any exceptions raised in the try block
202. What role does the finally block play in the Python exception
handling mechanism?
a. It is used to handle all types of exceptions
b. It handles only certain exceptions raised in the try block
c. It guarantees the execution of code whether an exception is raised
or not
d. It replaces the need for the try block
204. What role does the finally block play in Python’s exception
handling?
a. It only handles specific exceptions
b. It ensures the execution of specified code, whether an exception
occurs or not
c. It prevents any exception from occurring
d. It executes before the try block
212. In Python, what is the primary role of the finally block in pre-
defined clean-up actions?
a. To exclusively manage specific exceptions
b. To replace the try block entirely
c. To handle all errors raised in the try block
d. To execute necessary cleanup code whether an exception occurs
or not
221. In Python, what is the purpose of using the finally block for
pre-defined clean-up actions?
a. To exclusively handle specific exceptions
b. To terminate the program’s execution immediately
c. To execute necessary cleanup code, whether an exception occurs
or not
d. To suppress all exceptions in the try block
222. How does the finally block ensure effective error management
in Python?
a. By ignoring all exceptions raised in the code
b. By terminating the program’s execution instantly
c. By executing necessary cleanup code under all circumstances
d. By replacing the need for the try block
224. Which block lets you test a block of code for errors?
a. try
b. except
c. finally
d. None of the above
233. What type of error will be raised when the imported module is not
found?
a. ImportError
b. ModuleNotFoundError
c. AttributeError
d. NameError
239. What will be the output of the following Python code, if the time
module has already been imported?
4 + ‘3’
a. NameError
b. IndexError
c. ValueError
d. TypeError
Conclusion
Within the context of the study of programming education, this chapter
concentrated on Python’s Exception Handling as an essential resource. These
multiple-choice questions are an all-encompassing tool that enables students
to evaluate, reinforce, and expand their grasp of managing exceptions in
Python. The following chapter will include a comprehensive study of MCQs
about Python modules.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
41 b 91 b 141 c 191 b
42 b 92 d 142 d 192 b
43 c 93 c 143 a 193 b
44 c 94 d 144 b 194 c
45 d 95 c 145 a 195 c
46 a 96 b 146 a 196 b
47 d 97 d 147 c 197 c
48 b 98 b 148 b 198 c
49 c 99 d 149 b 199 a
Introduction
This chapter provides comprehensive MCQs of modules in Python
programming. It introduces the concept of modules, which are pre-written
Python code files that contain functions, variables, and classes that can be
utilized in other programs. The chapter covers importing modules, accessing
module attributes, and using built-in Python modules. It also includes
multiple-choice questions that assess the understanding of these essential
concepts. This chapter will help learners gain a solid foundation in working
with modules in Python and be able to utilize them in their programming
projects effectively.
Objectives
This chapter aims to provide learners with a comprehensive understanding of
Python modules, their significance, and how they can be used effectively in
programming. Through multiple-choice questions, this chapter aims to assess
learners’ knowledge and comprehension of various module-related concepts,
such as importing modules, creating custom modules, using built-in modules,
and modular programming practices. The chapter intends to familiarize
learners with module-related functionalities and techniques, allowing them to
enhance their coding skills and develop efficient and modular Python
programs.
Multiple choice questions
1. What is a Python module?
a. A Python module is a file containing Python code.
b. A Python module is a specific datatype in Python.
c. A Python module is a built-in function in Python.
d. A Python module is a collection of variables and functions.
10. Which module is used for handling dates and times in Python?
a. time c. calendar
b. datetime d. date
11. How can you uninstall a module in Python?
a. Remove the module file from the system.
b. Run the command “pip uninstall module_name” in the terminal.
c. Delete the module’s folder from the Python installation directory.
d. Run the command “sudo apt-get remove module_name” in the
terminal.
17. Which module is used for working with JSON data in Python?
a. json c. pyjson
b. datajson d. jsondata
18. What is the purpose of the urllib module in Python?
a. It is used for manipulating URLs.
b. It is used for performing mathematical operations.
c. It is used for file and directory manipulation.
d. It is used for sending emails.
23. Which module is used for working with Excel files in Python?
a. xlrd c. pyexcel
b. excelfile d. excel
24. What is the use of the collections module in Python?
a. It provides functionalities for working with complex numbers.
b. It provides functionalities for performing mathematical
operations.
c. It provides functionalities for handling special data types such as
queues and stacks.
d. It provides functionalities for networking operations.
26. Which module is used for working with CSV files in Python?
a. csv
b. pycsv
c. excelcsv
d. filecsv
28. How can you calculate the factorial of a number using the math
module in Python?
a. By using the function math.factorial(number)
b. By using the function math.calculate_factorial(number)
c. By using the function math.calculate(number)
d. By using the function math.factorialize(number)
29. Which module is used for working with XML data in Python?
a. xml
b. pyxml
c. xmlparse
d. xml.etree.ElementTree
32. How can you install a module in Python from a local file?
a. Run the command “pip install module_file_name” in the
terminal.
b. Use the import keyword to import the module directly from the
file.
c. Copy the module file to the Python installation directory.
d. Run the command “python install module_file_name” in the
terminal.
33. What is the use of the logging module in Python?
a. It provides functionalities for creating graphical user interfaces.
b. It provides functionalities for performing mathematical
operations.
c. It provides functionalities for logging messages during program
execution.
d. It provides functionalities for networking operations.
34. Which module is used for working with zip files in Python?
a. zipfile
b. zip
c. fileszip
d. compress
36. How can you check the current working directory in Python?
a. By using the os module’s cwd() function
b. By importing the pathlib module and using its functions
c. By using the sys module’s cwd() function
d. By using the os module’s getcwd() function
38. Which module is used for working with HTTP requests in Python?
a. requests
b. http
c. httprequest
d. urllib
41. Which module is used for working with audio files in Python?
a. pyaudio
b. audiofile
c. sound
d. wave
47. How can you import a specific function from a module in Python?
a. By using the keyword import function_name from module_name
b. By importing the module and then accessing the function using
dot notation
c. By using the function import_function(module_name,
function_name)
d. By using the keyword include function_name from
module_name.
53. How can you import all functions and variables from a module in
Python?
a. By using the import * keyword.
b. By importing the module and then using the import_all()
function.
c. By using the import_all_func(module_name) function.
d. By importing the module and then accessing the functions and
variables directly.
54. Which module is used for working with PDF files in Python?
a. PyPDF2
b. pdffile
c. pdf
d. pypdf
60. Which module is used for working with Excel files in Python
without using Excel?
a. openpyxl c. pyexcel
b. excelfile d. excel
61. What is the use of the argparse module in Python?
a. It provides functionalities for creating graphical user interfaces.
b. It provides functionalities for performing mathematical
operations.
c. It provides functionalities for parsing command-line arguments.
d. It provides functionalities for networking operations.
71. What does the term namespace refer to in the context of Python
modules?
a. The location where modules are stored
b. A container for variables and functions in a module
c. The process of importing a module
d. The name assigned to a module
77. In Python, how can you install a module that is not part of the
standard library?
a. By copying the module file to the Python installation directory
b. By including the module’s code in your program
c. By using the install_module command
d. By using a package manager like pip
82. How can you check if a module is installed on your system without
importing it?
a. check_module module
b. importlib.check(module)
c. pip check module
d. try: import module
84. How can you create a module that can be executed as a standalone
program?
a. By defining functions and variables
b. By using the standalone keyword
c. By including the __main__ block
d. By naming the module “main”
86. How can you prevent a module’s code from being executed when
imported?
a. By using the pass statement in the module
b. By including the __doc__ attribute
c. By placing the code in a separate directory
d. By using the if __name__ == “__main__”: block
88. How can you prevent a module’s code from being executed when
imported?
a. By using the pass statement in the module
b. By including the __doc__ attribute
c. By placing the code in a separate directory
d. By using the if __name__ == “__main__”: block
94. Which module provides support for working with dates and times
in Python?
a. calendar c. time
b. datetime d. date
95. In Python, what is the purpose of the globals() function?
a. It returns a list of all global variables
b. It returns the values of all global variables
c. It returns a dictionary of the current global symbol table
d. It returns the number of global variables
99. Which module is used for file input and output operations in
Python?
a. os c. io
b. fileio d. sys
100. What is the purpose of the random module in Python?
a. It provides random numbers for mathematical operations
b. It generates random passwords
c. It handles random exceptions
d. It is used for importing random modules
109. Which module is used for working with regular expressions and
patterns in Python?
a. regex c. re
b. pattern d. regexp
110. What is the purpose of the locals() function in Python?
a. It returns a list of all local variables
b. It returns the values of all local variables
c. It returns a dictionary of the current local symbol table
d. It is used for exception handling
113. Which module provides a way to create and process ZIP archives
in Python?
a. zipper c. zipfile
b. archive d. compressor
114. What is the purpose of the shutil module in Python?
a. It provides support for file and directory operations
b. It handles mathematical operations
c. It is used for creating graphical user interfaces
d. It is a part of the standard library
115. Which module is used for working with paths and directories in
Python?
a. pathlib
b. os.path
c. directory
d. files
117. How can you prevent a Python module from being executed when
imported?
a. Include a comment at the beginning of the module
b. Use the if __name__ == “__main__”: block
c. Add a special character before the module name
d. Wrap the entire module code in a function
120. How can you check the installed version of a Python module?
a. check_version(module_name)
b. version(module_name)
c. module_version(module_name)
d. pip show module_name
133. How does Python handle the issue of naming conflicts within
namespaces?
a. It automatically renames conflicting variables
b. It raises an exception
c. It uses the most recently defined variable
d. It allows multiple variables with the same name
134. What is a benefit of using namespaces in Python?
a. It allows the use of shorter variable names
b. It prevents naming conflicts and provides modularity
c. It reduces the need for indentation
d. It enables automatic garbage collection
138. What happens when two modules have a function with the same
name?
a. Python automatically renames one of the functions
b. It raises a syntax error
c. The function in the module that is imported later overwrites the
previous one
d. It causes a runtime error
142. How can you access a function func() from a module named
mymodule without importing the entire module?
a. import func from mymodule
b. mymodule.func()
c. from mymodule import func
d. access func in mymodule
149. How do you import functions and variables from one module into
another module?
a. By using the import statement
b. By defining the functions and variables with the same names in
both modules
c. By using the merge function
d. By copying and pasting the code from one module to another
151. How can you specify which functions and variables to import from
a module using the import statement?
a. By using the include keyword
b. By specifying the function or variable names after the import
keyword
c. By using the from keyword followed by the module name
d. By using the with statement
157. How can you create an alias for a module during import?
a. By using the rename keyword
b. By using the as keyword followed by the desired alias
c. By defining an alias in the module itself
d. By using the alias function
160. How can you create a Python module that can be executed both as
a standalone program and imported as a module?
a. By using the exec statement
b. By defining a class within the module
c. By using the __name__ attribute and the if __name__ ==
“__main__”: block
d. By using the main() function
188. How can you avoid name conflicts when importing multiple
modules in Python?
a. Rename the conflicting variables or functions
b. Import the modules in separate namespaces
c. Use the same name for different variables or functions
d. Ignore the conflicts and let Python handle it automatically
192. How can you check the list of available modules in Python?
a. By using the help() function
b. By executing the dir() function
c. By searching online documentation
d. By using the module_exists() function
197. How can you create a Python module that can be executed both as
a script and imported as a module?
a. By using the main() function as the entry point
b. By using a separate entry point file
c. By adding the module to the system path
d. By using the run() function from the module
198. How can you access the attributes and methods of a module
without importing it directly?
a. By using the importlib module’s inspect methods
b. By using the getattr() function with the module name
c. By importing the module as a string and using eval()
d. It is not possible to access module attributes without importing it
200. How can you install a module from the Python Package Index
(PyPI)?
a. By downloading the module file and running setup.py
b. By using the pip command with the module name
c. By importing the module with the package name
d. By running the install() function from the module
204. How can you install a module from a version control system in
Python?
a. By cloning the repository and running setup.py
b. By downloading the module as a zip file
c. By using the module’s subversion URL with the svn command
d. By running the install() function from the module
207. How can you create a module that can be imported as a package?
a. By defining a package-level __init__.py file
b. By adding subdirectories to the module file
c. By renaming the module file to __init__.py
d. By using the package() function from the module
209. A Python module is a file with the _____ file extension that
contains valid Python code.
a. .pymodule
b. .module
c. .pym
d. .py
Conclusion
In conclusion, the chapter on Python modules provided a comprehensive
understanding of how modules work in Python. We explored the various
module advantages, such as code reusability and easy maintenance. The
MCQs effectively tested our knowledge of importing modules, aliasing, and
accessing module members. Additionally, the chapter enlightened us on the
concept of built-in modules and their role in enhancing the functionality of
Python programs. By attempting these MCQs, we have improved our
understanding of Python modules and honed our problem-solving skills. The
next chapter will include MCQs about Python packages.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 a 51 c 101 d 151 c 201 a
11 b 61 c 111 c 161 d
12 a 62 a 112 c 162 b
13 a 63 a 113 c 163 b
14 b 64 a 114 a 164 c
15 b 65 c 115 a 165 b
16 a 66 c 116 c 166 c
17 a 67 c 117 b 167 c
18 a 68 c 118 c 168 b
19 a 69 c 119 b 169 c
20 a 70 c 120 d 170 d
21 c 71 b 121 c 171 b
22 a 72 d 122 a 172 b
23 a 73 a 123 b 173 c
24 c 74 a 124 b 174 c
25 a 75 d 125 c 175 d
26 a 76 c 126 b 176 a
27 c 77 d 127 d 177 d
28 a 78 c 128 a 178 a
29 d 79 d 129 a 179 c
30 c 80 b 130 a 180 c
31 a 81 a 131 b 181 a
32 a 82 d 132 d 182 a
33 c 83 b 133 b 183 b
34 a 84 c 134 b 184 b
35 c 85 a 135 c 185 d
36 d 86 d 136 c 186 a
37 c 87 a 137 b 187 a
38 a 88 d 138 c 188 a
39 d 89 d 139 c 189 b
40 c 90 c 140 c 190 a
41 d 91 c 141 a 191 a
42 b 92 a 142 c 192 b
43 a 93 c 143 b 193 a
44 c 94 b 144 b 194 a
45 a 95 c 145 b 195 c
46 c 96 c 146 d 196 a
47 a 97 a 147 b 197 a
48 a 98 a 148 c 198 b
49 c 99 c 149 a 199 d
Introduction
This chapter aims to test your knowledge and understanding of the concepts
related to Python packages. Python packages play a crucial role in organizing
and distributing code, allowing developers to efficiently manage and reuse
their codebase. Through a series of carefully crafted MCQs, this chapter will
assess your familiarity with topics such as package installation, importing
modules, package structure, and package management tools like pip. By
engaging with these MCQs, you will not only reinforce your understanding
of Python packages but also gain confidence in your ability to work with
them effectively. Let us dive in and test your knowledge in this exciting
chapter!
Objectives
Python packages are a vital component of the language, allowing users to
conveniently organize and distribute their code. This chapter explores the
concept of Python packages and their significance in programming. It covers
multiple-choice questions (MCQs) related to packages, and their
functionalities. Through these questions, readers will gain a deeper
understanding of how packages work, their advantages, and the different
ways they can be utilized to enhance the capabilities of their Python
programs.
Multiple choice questions
1. Which of the following statements about Python packages is true?
a. A package is a collection of modules
b. A package cannot contain any modules
c. Packages can only be imported in a specific order
d. Packages can be customized with any name
21. How can you check the installed packages and their versions in
Python?
a. pkg show c. package list
b. pip show d. pip list
22. Which of the following is not a standard Python package?
a. os c. requests
b. sys d. datetime
23. What is the purpose of the requests package in Python?
a. To access and manipulate web resources
b. To perform mathematical calculations
c. To generate graphical visualizations
d. To manage database connections
27. How can you install a specific version of a Python package using
pip?
a. pip install package_name==version_number
b. pip install version_number package_name
c. pip install package_name -v version_number
d. pip install -v package_name/version_number
32. Which package is commonly used for handling dates and times in
Python?
a. datetime c. calendar
b. time d. timedelta
33. What does the command "pip search package_name" do?
a. Searches for a specific package in the PyPI repository
b. Lists all installed packages containing the specified name
c. Searches for package updates
d. Installs the latest version of the specified package
34. How can you update an existing Python package to the latest
version using pip?
a. pip upgrade package_name
b. pip update package_name
c. pip install package_name --update
d. pip install --upgrade package_name
37. How can you install a package directly from a source distribution
using pip?
a. pip install package_name.tar.gz
b. pip install package_name.git
c. pip install package_name.zip
d. pip install package_name.source
41. How can you install a specific version of a Python package using
conda?
a. conda install package_name==version_number
b. conda install version_number package_name
c. conda install package_name -v version_number
d. conda install -v package_name/version_number
44. How can you install a package from a specific index using pip?
a. pip install package_name --index https://example.com
b. pip install package_name --source https://example.com
c. pip install package_name --repository https://example.com
d. pip install package_name --from https://example.com
47. How can you create a virtual environment in Python using venv?
a. python -m venv environment_name
b. venv create environment_name
c. virtualenv environment_name
d. python -m virtualenv environment_name
57. How can you install a Python package from a local directory using
pip?
a. pip install .
b. pip install package_name -l
c. pip install package_name --local
d. pip install package_name --directory.
58. What package allows you to work with Excel files in Python?
a. openpyxl c. xlwt
b. xlrd d. pandas
59. What does the command "pip install --no-cache-dir
package_name" do?
a. Disables caching during package installation
b. Removes the package cache
c. Installs the package without downloading any dependencies
d. Disables the package cache
60. How can you list all installed packages in Python using conda?
a. conda list c. conda search
b. conda show d. conda info
61. What does the command "pip install package_name --
user" do?
a. Installs the package for the current user only
b. Installs the package globally for all users
c. Installs the package without requiring administrative privileges
d. Installs the package with additional user-specific configurations
62. How can you install a package from a specific location using pip?
a. pip install package_name --location /path/to/package
b. pip install package_name --source /path/to/package
c. pip install package_name --path /path/to/package
d. pip install /path/to/package package_name
65. How can you install a specific version of a Python package using
conda?
a. conda install package_name=version_number
b. conda install version_number package_name
c. conda install package_name@version_number
d. conda install -v package_name/version_number
66. What package allows you to work with JSON data in Python?
a. json c. xml
b. requests d. csv
67. What does the command "pip install --no-deps
package_name" do?
a. Installs the package without installing any dependencies
b. Does not install the package
c. Removes all dependencies of the specified package
d. Forces the installation of all package dependencies
68. How can you install a package from a specific version control
repository using pip?
a. pip install package_name.git
b. pip install package_name --git
https://github.com/username/repo.git
c. pip install package_name --repo
https://github.com/username/repo.git
d. pip install package_name --version-control
https://github.com/username/repo.git
71. How can you add a package to the Python Path in Windows?
a. Set the PYTHONPATH environment variable
b. Modify the sys.path variable at runtime
c. Edit the registry to include the package path
d. Place the package in the Python installation directory
73. How can you list all installed packages in Python using pip?
a. pip list c. pip search
b. pip show d. pip info
74. What package allows you to work with XML data in Python?
a. xml c. xml.dom
b. xml.etree d. xmlrpc
75. What does the command "pip install --no-binary
package_name" do?
a. Installs the package from source instead of a pre-compiled binary
b. Disables the use of binary packages during installation
c. Removes the pre-compiled binary of the specified package
d. Forces the installation of binary packages, regardless of
availability
76. How can you install a package from a wheel distribution file using
pip?
a. pip install package_name.whl
b. pip install package_name
c. pip install package_name --wheel
d. pip install package_name --file package_name.whl
77. Which package is commonly used for working with CSV files in
Python?
a. csv
b. pandas
c. openpyxl
d. numpy
79. How can you install a package in development mode using pip?
a. pip install -e .
b. pip install package_name --dev
c. pip install package_name --develop
d. pip install package_name --development
80. What package allows you to work with compressed files (e.g., zip,
tar) in Python?
a. zipfile c. gzip
b. tarfile d. shutil
81. What does the command "pip install --log log.txt
package_name" do?
a. Logs the installation process to a file named log.txt
b. Installs the package with additional logging capabilities
c. Lists all available logs related to the specified package
d. Installs the specified package and stores the log in log.txt
82. How can you upgrade all installed packages in Python using pip?
a. pip install --upgrade-all
b. pip install --upgrade *
c. pip install --upgrade
d. pip install --upgrade-all-packages
83. Which package is commonly used for working with binary data in
Python?
a. struct c. bin
b. bytes d. binary
84. How do you uninstall all packages in Python?
a. pip uninstall all
b. remove all packages
c. uninstall all packages
d. pip freeze | xargs pip uninstall -y
98. How can you find the installation path of a package in Python?
a. Use the command “pip show packagename”
b. Use the command “python show package packagename”
c. import packagename and access the __path__ attribute
d. Use the command “show packagename path”
103. How do you import a module from a package with a long name?
a. import package.subpackage.module
b. from package.subpackage import module
c. include package.subpackage.module
d. import package.subpackage.module as mod
123. How do you run a Python script using the command line?
a. Use the command “python script.py”
b. Use the command “run script.py”
c. Use the command “python start script.py”
d. Use the command “execute script.py”
127. How do you specify the project version in the setup.py file?
a. Update the “version” parameter in the setup() function
b. Use the command “python setup.py version project_version”
c. Update the “__version__” attribute in the project’s main module
d. Use the command “python set version project_version”
130. How do you specify the project license in the setup.py file?
a. Update the “license” parameter in the setup() function
b. Use the command “python set license project_license”
c. Update the “__license__” attribute in the project’s main module
d. Use the command “python setup.py license project_license”
142. Which package is commonly used for creating and working with
virtual environments in Python?
a. venv c. env
b. virtualenv d. venvutil
143. The socket package in Python is used for ____________.
a. File I/O operations
b. Web development
c. Network programming
d. Data visualization
Conclusion
This chapter has provided a comprehensive set of MCQs which highlight
importance and functionality of packages in the Python programming
language. By understanding the concepts and techniques covered in this
chapter, developers can leverage the vast ecosystem of Python packages to
enhance their productivity and create robust and efficient applications. The
forthcoming chapter will provide a complete analysis of MCQs related to
object-oriented programming in Python.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Objected Oriented Programming (OOP) is a foundational paradigm in
software development that empowers programmers to model and organize
code using the principles of encapsulation, inheritance, and polymorphism. In
the context of Python, a versatile and dynamically typed language, the
incorporation of OOP principles enhances code clarity, maintainability, and
reusability. This chapter on multiple-choice questions for Object-Oriented
Programming in Python aims to provide learners with a comprehensive
exploration of OOP concepts within the Python programming language. The
MCQs delve into various aspects of Python’s implementation of OOP,
including class creation, inheritance, polymorphism, and encapsulation. As
learners navigate through these MCQs, they will gain a deeper understanding
of how to design and structure Python code using object-oriented principles,
empowering them to create robust and modular applications in the dynamic
and expressive Python programming environment.
Objectives
The objectives of this chapter are to assess learners’ comprehension of key
OOP concepts in Python, including class design, inheritance, polymorphism,
and encapsulation. By engaging with these MCQs, learners aim to strengthen
their ability to design modular and scalable Python code using object-
oriented principles, fostering proficiency in building robust applications.
32. How can you prevent other classes from creating instances of a
class in Python?
a. By defining the __init__ method as private.
b. By using the @abstractmethod decorator.
c. By defining the __new__ method as private.
d. By using the @staticmethod decorator.
50. Which method is called when two objects of a class are compared
using the == operator?
a. __init__ c. __main__
b. __eq__ d. __class__
51. What is the purpose of the @classmethod decorator in Python?
a. To define a class method in a class.
b. To define an abstract method in a class.
c. To define a static method in a class.
d. To define an instance method in a class.
75. What does the term Duck Typing mean in Python OOP?
a. It involves using classes to represent ducks in a program
b. It relies on the object’s behavior rather than its type
c. It is a type of polymorphism specific to ducks
d. None of the above
86. In Python, what does the term MRO stand for in the context of
multiple inheritance?
a. Multiple Reflection Order
b. Method Resolution Order
c. Module Registration Operation
d. None of the above
100. How can you create a default value for a constructor parameter in
Python?
a. By using the default keyword
b. By specifying the default value directly in the parameter list
c. By using the set_default method
d. None of the above
116. What is the term for a class that is inherited from in Python?
a. Parent class
b. Child class
c. Base class
d. Derived class
118. In Python, can a subclass have more attributes than its base class?
a. Yes, always
b. No, never
c. Yes, but only if the base class is abstract
d. None of the above
128. How can you prevent a method from being overridden in a Python
class?
a. By marking the method as final
b. By using the @final decorator
c. By using the @sealed decorator
d. None of the above
129. In Python, can a subclass have fewer attributes than its base class?
a. Yes, always
b. No, never
c. Yes, but only if the base class is abstract
d. None of the above
self.y = y
obj = MyClass()
a. SyntaxError: Too few arguments for init
b. TypeError: init() missing 2 required positional arguments
c. No error
d. AttributeError: ‘MyClass’ object has no attribute ‘x’
c = Circle()
print(c.diameter)
a. AttributeError: ‘Circle’ object has no attribute ‘diameter’
b. TypeError: ‘Circle’ object is not callable
c. No error
d. ValueError: name ‘diameter’ is not defined
self.y = y
p = Point(2, 3)
print(p.z)
161. What is the typical use case for a class method in Python?
a. Initializing instance variables
b. Performing operations on instance variables
c. Operating on class variables or creating class-level functionality
d. None of the above
162. How does a class method differ from a static method in Python?
a. Class methods can access instance variables, while static methods
cannot
b. Static methods can access class variables, while class methods
cannot
c. Class methods have access to the class itself, while static methods
do not
d. There is no difference between class methods and static methods
168. Which keyword is used to call a method from the parent class
within the child class?
a. super
b. parent
c. base
d. self
170. In Python, can a child class redefine a method inherited from the
parent class?
a. Yes, and it will overwrite the parent class method
b. No, child classes have read-only access to parent class methods
c. Only if the child class is also a parent class itself
d. It depends on the access specifier of the parent class method
172. In Python, can a child class access private variables and methods
of the parent class?
a. Yes, child classes have full access to all parent class members
b. No, child classes cannot access private members of the parent
class
c. Only if the parent class is defined within the same module as the
child class
d. It depends on the access specifier of the parent class members
174. In Python, can a child class have multiple parent classes of the
same name?
a. Yes, and it will merge the properties from all parent classes with
the same name.
b. No, Python does not support multiple parent classes with the
same name.
c. Only if the parent classes are defined within the same module as
the child class.
d. It depends on the specific implementation of the child class
178. In Python, can a child class inherit from multiple parent classes
with conflicting method signatures?
a. Yes, and it will result in an ambiguity error.
b. No, Python does not allow conflicting method signatures in an
inheritance chain.
c. Only if the child class is also a parent class itself.
d. It depends on the specific implementation of the child class and
the method resolution order.
190. In Python, can a child class override a method inherited from the
parent class and also call the parent class method within its
definition?
a. Yes, using the super() keyword
b. No, child classes cannot override and call parent class methods
simultaneously
c. Only if the child class is also defined as a parent class itself
d. It depends on the specific implementation of the child class and
method resolution order
192. In Python, can a child class inherit private variables from the
parent class?
a. Yes, child classes can inherit and access private variables of the
parent class
b. No, child classes cannot inherit private variables of the parent
class
c. Only if the private variables are marked as “protected” instead of
“private”
d. It depends on the specific implementation of the child class and
the access specifiers
194. In Python, can a child class override a method inherited from the
parent class without changing its functionality?
a. Yes, by using the pass keyword within the child class method
definition
b. No, Python does not allow method overriding without changing
functionality
c. Only if the child class is also defined as a parent class itself
d. It depends on the specific implementation of the child class and
method resolution order
198. In Python, can a child class have the same method name as the
parent class?
a. Yes, and it will overwrite the parent class method
b. No, child classes cannot have the same method name as the
parent class
c. Only if the child class is also defined as a parent class itself
d. It depends on the specific implementation of the child class and
method resolution order
208. In Python, can a child class override a method inherited from the
parent class and also call the parent class method within its
definition?
a. Yes, using the super() keyword
b. No, child classes cannot override and call parent class methods
simultaneously
c. Only if the child class is also defined as a parent class itself
d. It depends on the specific implementation of the child class and
method resolution order.
210. In Python, can a child class inherit private variables from the
parent class?
a. Yes, child classes can inherit and access private variables of the
parent class
b. No, child classes cannot inherit private variables of the parent
class
c. Only if the private variables are marked as “protected” instead of
“private”
d. It depends on the specific implementation of the child class and
the access specifiers
212. In Python, can a child class override a method inherited from the
parent class without changing its functionality?
a. Yes, by using the pass keyword within the child class method
definition.
b. No, Python does not allow method overriding without changing
functionality.
c. Only if the child class is also defined as a parent class itself.
d. It depends on the specific implementation of the child class and
method resolution order.
235. Which of the following is not a valid use case for decorators in
Python?
a. Caching and memoization
b. Input validation and error checking
c. Logging and performance monitoring
d. Changing the syntax or behavior of the Python language itself
250. What is the typical use case for a static method in Python?
a. To create a new instance of a class
b. To perform operations on class variables
c. To define private methods
d. To create class-level functionality independent of instance
variables
Conclusion
In conclusion, the Object-Oriented Programming in this chapter serves as a
valuable resource for learners seeking to deepen their understanding of OOP
principles in the context of Python. These questions provide a structured
approach to assessing and reinforcing knowledge of key concepts such as
class design, inheritance, polymorphism, and encapsulation. As learners
navigate through these questions, they gain practical insights into leveraging
OOP for modular and maintainable code. The forthcoming chapter will
provide a complete analysis of MCQs related to GUI programming in
Python.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Graphical user interfaces are essential components of modern software
applications, enabling users to interact with the program intuitively and
visually. This chapter comprehensively explores GUI development using
Python, designed to equip you with essential knowledge through MCQs.
From foundational concepts to advanced techniques, this chapter delves into
creating interactive and visually appealing interfaces using libraries like
Tkinter, PyQt, or Kivy. Whether you are a novice eager to grasp the basics or
an experienced developer aiming to enhance your GUI-building skills, this
chapter will guide you through various MCQs, ensuring a solid understanding
of GUI development in Python. Get ready to embark on a journey that
unlocks the power of Python for crafting dynamic and user-friendly
interfaces!
Objectives
The objectives of this chapter are multifold, aiming to provide a
comprehensive understanding of GUI development in Python. Firstly, it
intends to introduce the fundamental concepts of GUIs, covering topics such
as widget usage, event handling, and layout management. The chapter aims
to familiarize readers with various Python GUI libraries, elucidating their
unique features and functionalities through MCQs. Furthermore, it seeks to
delve into advanced GUI development techniques, including data
visualization, integration of multimedia elements, and responsive design
principles. Ultimately, these objectives converge to empower learners,
enabling them to design, create, and manipulate Python-based Graphical User
Interfaces proficiently.
35. How can you change the text color of a tkinter widget?
a. setTextColor() c. configure()
b. colorize() d. setFgColor()
36. Which widget is used to display multiple lines of text in tkinter?
a. Entry c. Label
b. Text d. MultiLineBox
37. What function is used to clear the content of an Entry widget in
tkinter?
a. clear() c. clearContent()
b. delete() d. erase()
38. How can you set the alignment of a tkinter widget within its
container?
a. align() c. configure()
b. setAlignment() d. place()
39. Which module in tkinter is used to create menus?
a. tkinter.menu
b. tkinter.options
c. tkinter.dialog
d. tkinter.menuwidget
47. How can you change the font style of a tkinter widget?
a. setFontStyle() c. setStyle()
b. configure() d. fontStyle()
48. Which event is triggered when a mouse button is released in
tkinter?
a. <Button-1>
b. <ButtonRelease-1>
c. <MouseClick-1>
d. <MouseRelease-1>
50. How can you set the visibility of a tkinter window to full screen?
a. fullScreen() c. fullscreen()
b. maximize() d. setFullScreen()
51. Which function is used to display an info box/dialog in tkinter?
a. messagebox.info()
b. tkinter.info()
c. dialog.info()
d. messagebox.dialog()
53. How can you set the border color of a tkinter widget?
a. setBorderColor()
b. border()
c. configure()
d. bdColor()
57. How can you set the image of a tkinter Button widget?
a. setImage()
b. configure()
c. setImageIcon()
d. configure(image=...)
58. Which event is triggered when the mouse pointer enters a tkinter
widget?
a. <MouseEnter> c. <Enter>
b. <MouseOver> d. <Motion>
59. What is the purpose of the ListBox widget in tkinter?
a. To display a list of items
b. To create lists
c. To organize widgets in a list-like structure
d. To select options from a list
60. How can you disable user interaction with a tkinter widget?
a. deactivate() c. setEnabled()
b. disable() d. block()
61. What is the purpose of a graphical user interface (GUI) in Python?
a. To provide an interactive interface for users to interact with the
program
b. To perform complex calculations in the background
c. To convert Python code into an executable file
d. To generate graphs and charts
62. What is the main window of a tkinter GUI application called?
a. Root window c. Parent window
b. Main window d. Child window
63. Which method is used to create a button widget in tkinter?
a. create_button() c. Button()
b. custom_button() d. add_button()
64. Which widget is used to display text in tkinter?
a. Label c. TextBox
b. Text d. Display
65. How can you add a menu bar to a tkinter GUI application?
a. Using the add_menu_bar() method
b. Using the create_menu_bar() method
c. Using the configure_menu_bar() method
d. Using the Menu() widget
70. Which method is used to start the main event loop in tkinter?
a. start_loop() c. main()
b. run() d. mainloop()
71. What is the purpose of the grid() method in tkinter?
a. To place widgets in a grid-like structure
b. To change the background color of a widget
c. To resize the window
d. To add an image to the GUI
116. How can you set the background color of a panel in wxPython?
a. Using the SetBackgroundColour() method
b. Using the SetColor() method
c. Using the SetBackgroundColor() method
d. Using the SetBgColor() method
128. Which method is used to bind the ‘Enter’ key press event in
Tkinter?
a. bind(‘<Enter>’)
b. bind(‘<Return>’)
c. bind(‘<Key>’)
d. bind(Enter)
129. What is the event type for a mouse click event in Tkinter?
a. click c. button
b. mouse d. Button-1
130. How can you change the cursor style when it hovers over a widget
in Tkinter?
a. By using the ‘event.cursor()’ method
b. By updating the ‘widget.cursor’ attribute
c. By using the ‘widget.bind()’ method with ‘CursorEnter’ event
d. It cannot be changed
132. What is the event type for a key press event in Tkinter?
a. ‘keypress’ c. ‘key_press’
b. ‘key’ d. ‘Key-1’
133. How can you bind a mouse right-click event in Tkinter?
a. bind(‘<MouseButton-1>’)
b. bind(‘<MouseButton-2>’)
c. bind(‘<MouseButton-3>’)
d. bind(‘<Button-2>’)
134. How can you bind an event to happen when the mouse enters a
specific widget in Tkinter?
a. bind(‘<Enter>’)
b. bind(‘<MouseEnter>’)
c. bind(‘<MouseIn>’)
d. bind(‘<Motion>’)
135. What is the event type for a mouse motion event in Tkinter?
a. mouse
b. motion
c. move
d. Motion
136. How can you bind an event to happen when the mouse leaves a
specific widget in Tkinter?
a. bind(<Leave>)
b. bind(<Exit>)
c. bind(<MouseOut>)
d. bind(<MotionLeave>)
137. What is the event type for a mouse double-click event in Tkinter?
a. click c. dblclick
b. double-click d. ButtonRelease-1
138. Which method is used to handle a widget drag event in Tkinter?
a. on_drag()
b. handle_drag()
c. drag_event()
d. bind(<B1-Motion>)
139. How can you bind an event to a specific keyboard key press in
Tkinter?
a. bind(<KeyPress>)
b. bind(<KeyRelease>)
c. bind(<Key>)
d. bind(<Keyboard>)
155. What is the purpose of using all uppercase letters for widget
names?
a. To improve code readability
b. To indicate a specific type of widget
c. To differentiate between parent and child widgets
d. It is not a recommended naming convention in Python
165. How do you create a fixed-size widget using the grid layout?
a. Set the width and height attributes
b. Use the pack() method
c. Use the sticky parameter in grid()
d. None of above
168. What is the advantage of using the pack manager over the grid
manager?
a. Pack manager offers more control over widget placement
b. Grid manager is simpler to use
c. Pack manager automatically resizes widgets
d. No difference
171. How do you specify the size of a widget using the pack manager?
a. Use the width and height parameters
b. Use the fill parameter
c. Use the expand parameter
d. Use x and y parameters
176. What is the default value of the sticky parameter in the grid
layout?
a. “ns” c. nsew
b. “ew” d. None of the above
177. How do you create a widget that spans multiple rows or columns
in the grid layout?
a. Use the rowspan or columnspan parameter
b. Use the pack() method
c. Use the fill parameter
d. Use position() method
178. Which method is used to adjust the size of a widget in the pack
layout?
a. resize() c. pack_configure()
b. configure() d. none()
179. How do you create a fixed-size widget using the place layout?
a. Set the width and height attributes
b. Use the pack() method
c. Use the sticky parameter
d. Use the size() method
181. When using the Tkinter library, which method is used to bind an
event to a widget?
a. bind_event() c. bind()
b. attach_event() d. connect()
182. Which method is used to retrieve the current value of a Scale
widget in Tkinter?
a. get() c. retrieve()
b. fetch() d. value()
183. In Tkinter, how do you create a button that executes a specific
function when clicked?
a. button = Button(text=”Click Me”, command=my_function)
b. button = Button(text=”Click Me”).bind(my_function)
c. button = Button(text=”Click Me”).onclick(my_function)
d. button = Button(text=”Click Me”).execute(my_function)
185. In Tkinter, what event is triggered when the user closes a window?
a. on_close c. destroy
b. close_event d. exit_event
186. Which method is used to change the font of a text widget in
Tkinter?
a. set_font() c. configure()
b. change_font() d. font()
187. How do you create a radio button in Tkinter?
a. radio_button = Radiobutton(text=”Radio”)
b. radio_button = Button(text=”Radio”)
c. radio_button = RadioButton(text=”Radio”)
d. radio_button = Checkbutton(text=”Radio”, radio=True)
191. Which method is used to set the maximum value of a progress bar
in Tkinter?
a. set_max() c. set_maximum()
b. maximum() d. configure()
192. What does the pack() method do in Tkinter?
a. Packs the GUI elements together closely
b. Packs the GUI elements into a grid layout
c. Packs the GUI elements into a horizontal line
d. Packs the GUI elements into a vertical line
200. Which method is used to get the current text in an Entry widget in
Tkinter?
a. entry.get_text()
b. entry.get()
c. entry.text()
d. entry.get_entry()
212. Which method can be used for handling exceptions in Python GUI
programming?
a. try...except blocks
b. if...else statements
c. finally clauses
d. All of the above
Conclusion
This chapter covers essential concepts such as creating windows, handling
events, and designing user-friendly interfaces. It also includes a wide range of
multiple-choice questions that test readers’ understanding of the material,
offering valuable opportunity for self-assessment. Overall, this chapter is an
excellent resource for beginners learning GUI programming in Python which
reinforces essential concepts through well-designed, interactive quizzes. The
forthcoming chapter will discuss MCQs related to Machine learning concepts
in Python.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
This chapter embarks on a dynamic exploration of the intricate landscape
where Python and machine learning converge explore the realm of
algorithms, models, and methodologies that empower machines to learn and
make predictions based on data. This chapter unravels the core principles
behind supervised and unsupervised learning, ensemble methods, feature
engineering, evaluation metrics, and more, from foundational concepts to
advanced techniques. Prepare to navigate the complexities of model tuning,
data preprocessing, and the art of effectively harnessing Python’s versatile
libraries to craft intelligent systems. Each question in this chapter serves as a
gateway to understanding the synergy between Python’s prowess and the
intricate mechanisms driving the realm of machine learning.
Objectives
The objective of this chapter is to provide a comprehensive and insightful
journey into the realm of machine learning using Python as the primary tool.
This chapter aims to equip readers with a profound understanding of
fundamental machine learning concepts, advanced techniques, and practical
applications through a series of thought-provoking multiple-choice questions.
By navigating these questions, learners will gain a deep insight into various
algorithms, data preprocessing methods, model evaluation, feature
engineering, and the intricate nuances of applying Python libraries for
implementing machine learning solutions. The overarching goal is to
empower readers with the knowledge and skills necessary to confidently
approach and solve real-world problems using machine learning
methodologies in a Python environment.
72. Machine learning is used in virtual assistants like Siri and Alexa
for:
a. Detecting earthquakes
b. Recognizing faces
c. Answering user queries or commands
d. Playing music
73. Which of the following industries has seen increased efficiency and
productivity through machine learning applications?
a. Manufacturing
b. Education
c. Sports
d. Music
164. What does the slope of the regression line represent in linear
regression?
a. Intercept value
b. Predicted output value
c. Rate of change in the output for a unit change in the input
d. None of the above
167. Which function is used to create a scatter plot with the regression
line in Matplotlib?
a. plt.scatter() c. plt.regplot()
b. plt.plot() d. plt.lineplot()
168. What is the equation for a simple linear regression line?
a. y = mx + c
b. y = mx
c. y = ax^2 + bx + c
d. y = ab^x
198. In nonlinear regression, what does the term local minima refer to?
a. The point where the regression line intersects the y-axis
b. The lowest point on the regression curve
c. Different regression lines with different local minimum points
d. A point where the gradient of the error function is zero
237. What is the advantage of using decision trees for feature selection?
a. They inherently perform feature selection
b. They ignore redundant features automatically
c. They require fewer computational resources
d. None of the above
270. What does the parameter gamma control in the RBF kernel of
SVM?
a. The width of the Gaussian kernel
b. The regularization parameter
c. The degree of the polynomial kernel
d. None of the above
288. Which metric is often used for regression models to evaluate the
goodness of fit?
a. Mean Absolute Error (MAE)
b. R-squared
c. Mean Squared Error (MSE)
d. All of the above
294. Which method in scikit-learn is used to split data into training and
testing sets?
a. split_data()
b. train_test_split()
c. create_train_test()
d. separate()
306. Which Matplotlib method is used to add labels to the x-axis and y-
axis?
a. plt.xlabel() and plt.ylabel()
b. plt.add_xaxis_label() and plt.add_yaxis_label()
c. plt.x_label() and plt.y_label()
d. plt.axis_labels()
313. What NLTK module is used for stemming words in a text to their
root form?
a. nltk.stem c. nltk.lemmatize
b. nltk.stemming d. nltk.stemmer
314. Which NLTK method is used to find the frequency distribution of
words in a text?
a. nltk.word_frequency()
b. nltk.freq_dist()
c. nltk.FreqDist()
d. nltk.frequency_distribution()
327. What does the command sudo prefixing the installation command
indicate in Python?
a. Unix-based system?
b. Installation for a specific user
c. Root privileges for installation
d. Uninstallation of the package
e. Installation within a virtual environment
337. What does the NLTK downloader enable users to access and
download?
a. NLTK libraries only
b. NLTK documentation
c. Additional datasets, corpora, and models
d. External Python packages
339. Which NLTK method is used to verify the installation and version
information on a Windows system?
a. nltk version c. python -m nltk
b. pip show nltk d. nltk.about()
340. How can NLTK be installed using Anaconda on Windows?
a. conda install -c anaconda nltk
b. pip install nltk-anaconda
c. anaconda install nltk
d. nltk install --conda
348. What does the term feature scaling aim to achieve in machine
learning?
a. Reducing the number of features in the dataset
b. Normalizing feature values to a similar scale
c. Adding new features to the dataset
d. Removing redundant features from the dataset
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
Clustering is a fundamental technique in data analysis where similar data
points are grouped into clusters based on their features and similarity
measures. This chapter will explore the concepts and methodologies of
clustering algorithms using the Python programming language. This chapter
is designed to test and enhance your understanding of various clustering
techniques such as k-means, hierarchical clustering, and DBSCAN, among
others, and their practical applications. By answering the MCQs in this
chapter, you will validate your knowledge and develop a deeper
comprehension of clustering algorithms and their implementation in Python.
Objectives
This chapter aims to provide readers with a comprehensive understanding of
the concepts and techniques used in clustering analysis. The chapter aims to
equip readers with the knowledge and practical skills to apply various
clustering algorithms, evaluate their performance, and interpret the results
using Python. Through a series of MCQs, this chapter aims to reinforce the
key concepts covered, test the readers’ understanding, and enhance their
problem-solving abilities in clustering analysis.
67. What does the term elbow method refer to in the context of K-
means clustering?
a. A technique used to determine the optimal number of clusters
b. A technique used to measure the cluster compactness
c. A technique used to measure the cluster separation
d. A technique used to estimate the cluster sizes
81. Which clustering algorithm does not require defining the distance
threshold and minimum number of points?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
88. Which clustering algorithm can handle varying cluster sizes and
densities?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. DBSCAN
d. Spectral clustering
107. How does Ward’s method differ from other linkage criteria in
hierarchical clustering?
a. It maximizes the within-cluster sum of squares
b. It minimizes the within-cluster sum of squares
c. It minimizes the between-cluster sum of squares
d. It maximizes the between-cluster sum of squares
160. When evaluating a classification model, the term recall refers to:
a. The ability of the model to correctly identify the positive class
b. The ability of the model to correctly identify the negative class
c. The ability of the model to correctly identify both positive and
negative classes
d. The ability of the model to classify a sample in either positive or
negative class
191. Which technique is commonly used to deal with the cold start
problem in recommender systems?
a. Collaborative filtering
b. Content-based filtering
c. Popularity-based filtering
d. Demographic filtering
219. How can you access the cluster labels after performing K-Means
clustering in Scikit-learn?
a. model.centroids_
b. model.labels_
c. model.clusters_
d. model.predictions_
245. Which library is commonly used for implementing the Mean Shift
clustering algorithm in Python?
a. Scikit-learn c. StatsModels
b. SciPy d. OpenCV
246. What does the bandwidth parameter control in Mean Shift
clustering?
a. Number of clusters
b. Width of the kernel
c. Learning rate
d. Convergence threshold
Conclusion
This chapter covers the foundational concepts of clustering, such as distance
metrics, similarity measures, and evaluation methods, along with practical
applications and implementations using Python libraries like scikit-learn and
the K-means clustering algorithm. These multiple choice questions enhance
the reader’s understanding and retention of the material, allowing readers to
test their knowledge and reinforce key concepts. Whether for beginners or
experienced Python programmers, this chapter serves as a valuable resource
to gain proficiency in clustering techniques and their implementation through
Python programming. The forthcoming chapter will discuss MCQs related to
various applications of Python.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
This chapter is a dynamic and comprehensive exploration of the diverse
applications of Python in various domains. This chapter covers a wide range
of practical scenarios through thoughtfully crafted multiple choice questions.
Topics include data analysis, machine learning, web development,
automation, and more, providing readers with a holistic view of Python’s
versatility. By engaging with these MCQs, readers test their theoretical
knowledge and gain practical insights into how Python can be applied in real-
world situations. This chapter serves as an invaluable resource for those
looking to expand their proficiency in Python by delving into its practical
applications across different fields, making it an essential read for anyone
eager to harness the power of Python.
Objectives
The primary goal of this chapter is to familiarize readers with real-world
scenarios and challenges they will encounter in data analysis, machine
learning, web development, automation, and more. The chapter aims to test
and reinforce theoretical knowledge while emphasizing the practical
application of Python in solving tangible problems. Presenting MCQs
focused on varied applications encourages readers to think critically, apply
Python programming skills, and gain hands-on experience. Overall, the
chapter’s objectives are to equip readers with a well-rounded skill set,
enabling them to confidently leverage Python for practical solutions in
various professional domains.
17. What does the term ORM stand for in the context of Python
applications?
a. Object-Relational Mapping
b. Object-Responsive Methods
c. Online Resource Management
d. Operating Room Modeling
20. Which Python library is often used for interacting with APIs?
a. Requests c. Matplotlib
b. NumPy d. SymPy
21. What is the primary purpose of the Django web framework in
Python?
a. Data analysis
b. Game development
c. Web development
d. Machine learning
26. Which Python library is commonly used for handling dates and
times?
a. datetime c. NumPy
b. Requests d. Flask
27. What is the purpose of the asyncio module in Python?
a. Data analysis
b. Asynchronous I/O operations
c. Game development
d. Machine learning
45. What does the term CI/CD stand for in the context of Python
development?
a. Continuous Integration/Continuous Development
b. Computer Input/Computer Display
c. Cryptographic Identity/Code Deployment
d. Code Inspection/Code Debugging
46. Which Python library is commonly used for working with Excel
files?
a. Openpyxl
b. Pandas
c. NumPy
d. Matplotlib
72. Which Pygame function is used for blitting (drawing) one surface
onto another?
a. pygame.blit()
b. pygame.surface.blit()
c. pygame.draw.blit()
d. pygame.Surface.blit()
76. Which Pygame function is used to set the caption of the game
window?
a. pygame.set_caption()
b. pygame.display.set_caption()
c. pygame.window.set_caption()
d. pygame.caption.set()
94. What does the term HTML parsing refer to in the context of web
scraping?
a. Extracting data from images
b. Analyzing the structure of a web page
c. Sending HTTP requests to a server
d. Interacting with JavaScript functions
95. Which HTTP method is typically used for retrieving data in web
scraping?
a. POST c. PUT
b. GET d. DELETE
96. What is the purpose of the User-Agent header in web scraping?
a. It specifies the user’s IP address
b. It identifies the web browser and operating system
c. It encrypts the data transmitted between the client and server
d. It defines the content type of the HTTP request
97. Which Python module allows you to interact with HTML and
XML documents in a structured way?
a. json
b. re
c. html.parser
d. random
98. What is the purpose of the robots.txt file in the context of
web scraping?
a. It contains information about the website’s server
b. It provides rules for search engine crawlers
c. It stores user login credentials
d. It contains the HTML code of the website
101. What does the term rate limiting refer to in web scraping?
a. Controlling the speed of HTTP requests to avoid being blocked
b. Limiting the number of web pages to be scraped
c. Specifying the time zone for the scraped data
d. Restricting access to certain parts of a website
109. In web scraping, what is the purpose of the robots meta tag?
a. Controlling the behavior of search engine crawlers
b. Hiding content from web scrapers
c. Encrypting data transmitted between the client and server
d. Defining the structure of a web page
110. What does the term XPath refer to in the context of web scraping?
a. A programming language
b. A file format for storing web data
c. A navigation technique for XML documents
d. A web browser extension
119. What does the term web crawling refer to in the context of web
scraping?
a. Extracting data from web pages
b. Scanning a website to index its content
c. Generating random HTTP requests
d. Making HTTP requests to a server
129. What does the term web scraping etiquette refer to?
a. Following ethical practices in web scraping
b. Using the same user-agent for all requests
c. Scraping without the website owner’s consent
d. Ignoring the robots.txt file
135. Which Python library is commonly used for working with Excel
files in business applications?
a. Requests c. SQLAlchemy
b. Openpyxl d. NumPy
136. How can Python be utilized for customer relationship
management (CRM) in business?
a. Sending and receiving emails
b. Analyzing customer data and trends
c. Generating 3D graphics
d. Playing multimedia files
137. What does the term ERP stand for in the context of business
applications?
a. External Resource Processing
b. Enterprise Resource Planning
c. Error Recovery Protocol
d. Efficient Routing Protocol
152. Which Python library is commonly used for data cleaning and
preprocessing in business applications?
a. NumPy c. Matplotlib
b. Pandas d. Scikit-learn
153. How does Python contribute to customer engagement in business
applications?
a. By creating virtual reality simulations
b. By analyzing customer behavior and preferences
c. By generating random numbers
d. By creating mobile games
159. Which Python library is commonly used for time series analysis in
business applications?
a. SciPy c. Pandas
b. Statsmodels d. Matplotlib
160. How does Python contribute to sales forecasting in business
applications?
a. By creating virtual reality simulations
b. By analyzing historical sales data and predicting future trends
c. By generating random numbers
d. By creating mobile games
172. In business applications, how can Python be used for social media
analytics?
a. By creating virtual reality simulations
b. By analyzing and extracting insights from social media data
c. By generating random numbers
d. By creating mobile applications
173. Which Python library is commonly used for machine learning in
business applications?
a. Pandas
b. Scikit-learn
c. Matplotlib
d. Statsmodels
179. Which Python library is commonly used for video editing and
manipulation?
a. PyDub c. OpenCV
b. MoviePy d. Matplotlib
180. What is the primary purpose of the ffmpeg library in the context
of audio and video processing?
a. Image manipulation
b. Video compression
c. Audio compression
d. File format conversion
193. Which Python library is commonly used for working with audio
files in various formats?
a. PyDub c. SoundPy
b. WaveLib d. AudioTools
194. What is the purpose of the cv2.Canny function in OpenCV?
a. Blur images
b. Detect edges in images
c. Resize images
d. Convert images to grayscale
203. Which Python library is commonly used for working with audio
signals in the frequency domain?
a. NumPy c. SciPy
b. PyDub d. FrequencyPy
204. Which Python library is commonly used for Computer-Aided
Design (CAD) applications?
a. PyAutoCAD c. PyCAD
b. CADLib d. AutoPy
205. In the context of CAD, what does the term parametric design
mean?
a. Designing geometric shapes
b. Designing based on parameters and constraints
c. Designing with CAD libraries only
d. Designing in a 3D environment
216. Which Python library is often used for creating technical drawings
and schematics?
a. PySchematic c. SchemPy
b. CADDraw d. PyTechDraw
217. What does the term CAD kernel refer to in the context of CAD
programming?
a. The central processing unit of a CAD system
b. The core geometric modeling engine
c. A library for rendering CAD images
d. A programming language for CAD applications
220. Which Python library is commonly used for working with STEP
files in CAD applications?
a. PySTEP c. CADSTEP
b. STEPpy d. PyCADFile
221. What is the primary function of the pyCADCAM library in
Python?
a. Creating technical drawings
b. Computer-Aided Design and Manufacturing
c. 3D modeling
d. CAD file conversion
222. Which Python library is often used for creating custom CAD
applications?
a. CADLib c. CADApp
b. PyCADCustom d. CustomCAD
223. In CAD, what does rendering refer to?
a. Creating a 2D sketch
b. Converting 3D models to 2D
c. Generating a visual representation of a 3D model
d. Performing boolean operations on shapes
230. Which Python library is often used for converting CAD files to
different formats?
a. CADConvert
b. PyCADConverter
c. ConvertLib
d. CADFileConvert
243. What does the term I2C stand for in embedded systems?
a. Input to Computer
b. Interface to Controller
c. Inter-Integrated Circuit
d. Input/Output Communication
244. Which Python library is commonly used for controlling servos and
motors in embedded systems?
a. PyMotorControl c. MicroServo
b. MotorLib d. ServoControl
245. What is the purpose of the time.sleep function in embedded
systems programming?
a. Input/output operations
b. Delaying program execution
c. Managing hardware pins
d. Creating real-time clocks
Conclusion
In summary, the Python Applications MCQ chapter comprehensively
explores practical applications across various domains within the Python
programming language. This chapter aims to equip readers with diverse skill
sets by presenting MCQs covering real-world scenarios and challenges.
Readers have engaged with questions ranging from data analysis and
machine learning to web development and automation. The chapter not only
evaluates their theoretical understanding but also encourages the application
of Python in solving tangible problems. By navigating through these MCQs,
readers have honed their problem-solving skills and gained insights into how
Python can be effectively utilized across different domains. As a result, this
chapter is a valuable resource for individuals at various proficiency levels,
from beginners aiming to understand Python’s versatility to experienced
developers seeking to broaden their application-specific knowledge within
the Python ecosystem. The forthcoming chapter will discuss MCQs related to
various Python error-finding problems.
Introduction
This chapter is designed to enhance the proficiency of Python developers by
presenting a curated collection of MCQs focused on identifying and resolving
errors in Python code. This chapter is an invaluable tool for developers at
various skill levels, from beginners aiming to strengthen their debugging
skills to seasoned programmers seeking to refine their error-spotting
capabilities. The carefully crafted questions cover a spectrum of common
errors, spanning syntax, runtime, and logical issues, comprehensively
examining potential pitfalls in Python programming.
Objectives
This chapter aims to systematically expose readers to various error scenarios,
including syntax errors, runtime exceptions, and logical flaws. By engaging
with these MCQs, readers will develop a keen eye for recognizing error
patterns, fortifying their debugging skills. Additionally, the chapter seeks to
deepen the understanding of common programming pitfalls and foster a
proactive mindset toward identifying and addressing errors during code
development. The objectives are aligned with the broader goal of equipping
readers with the expertise to produce more robust and error-resistant Python
code, promoting a disciplined approach to software development.
Multiple choice questions
1. Which of the following options correctly fixes the error in this
code?
numbers = [1, 2, 3, 4, 5]
for number in numbers
print(number)
a. for number in numbers:
b. for number in numbers::
c. for number in numbers;
d. for number in numbers {
11. Which of the following options correctly fixes the error in this
code:
1. x = 7
2. if x % 2 = 0:
3. print("x is even")
a. No error
b. if x mod 2 = 0
c. if x % 2 == 0 :
d. x=10
16. Which of the following options would fix the code given:
list = [1, 2, 3]
print(list[3])
a. Change list to my_list
b. Use len(list) to get the length of the list
c. Access a valid index within the list’s range
d. Remove the square brackets around 3
21. Which of the following options correctly fixes the error in this
code:
for i in range(10)
print(i)
a. for i in range(10):
print(i)
b. for i range(10)
print(i)
c. for i in range(10)
print(i)
d. for i in range(10): print(i)
22. Which of the following options correctly fixes the error in this
code:
my_dict = {1:"one",2:"two",3:"three"}
my_dict.get(4)
a. my_dict = {1:”one”,2:”two”,3:”three”} print(my_dict.get(4,”key
does not exist”))
b. my_dict = {1:”one”,2:”two”,3:”three”,4:”four”}
my_dict.get(4)
c. my_dict = {1:”one”,2:”two”,3:”three”}
my_dict[4]
d. my_dict = {1:”one”,2:”two”,3:”three”}
print(my_dict[4])
23. Which of the following options correctly fixes the error in this
code:
print("Hello \n world!")
a. print(“Hello world!”)
b. print(“Hello \n world!”)
c. print(“Hello /n world!”)
d. print(“Hello world!”)
24. Which of the following options correctly fixes the error in this
code:
x = 1
if x = 1: print("x is 1")
a. x = 1
if x == 1:
print(“x is 1”)
b. x = 1
if x = 1:
print(“x is 1”)
c. x = 1
if 1 == x:
print(x is 1)
d. x = 1
if x = 1
print(“x is 1”)
25. Which of the following options correctly fixes the error in this
code:
nums = [1, 2]
nums.append(3, 4)
a. nums = [1, 2]
nums.append([3, 4])
b. nums = [1, 2]
nums.push(3, 4)
c. nums = [1, 2]
nums.extend([3, 4])
d. nums = [1, 2]
nums.insert(2, 3)
nums.insert(3, 4)
26. Which of the following options correctly fixes the error in this
code:
d = {"one": 1, "two": 2}
print(d["three"])
a. d = {“one”: 1, “two”: 2}
print(d.get(“three”))
b. d = {“one”: 1, “two”: 2, “three”: 3}
print(d[“three”])
c. d = {“one”: 1, “two”: 2}
d.update({“three”: 3})
print(d[“three”])
d. d = {“one”: 1, “two”: 2}
d[“three”] = 3
print(d[“three”])
27. Which of the following options correctly fixes the error in this
code:
x = 10
if x > 5
print("Big number")
a. x = 10
if [x > 5:
print(“Big number”)
b. x = 10
if x > 5:
print(“Big number”)
c. x = 10
if x > 5
print(“Big number”):
d. x = 10
elif x > 5:
print(“Big number”)
28. Which of the following options correctly fixes the error in this
code:
x = "hello"
print(Hello)
a. x = “hello”
print(x)
b. x = “hello”
print(“Hello”)
c. hello = “hello”
print(hello,x)
d. x = “Hello”
print(x)
29. Which of the following options correctly fixes the error in this
code:
1. numbers = [1, 2, 3, 4, 5]
2. for i in numbers
3. print(i)
a. No error
b. Missing colon after for i in numbers
c. Incorrect indentation in line 3
d. Missing parentheses in numbers
30. Which of the following options correctly fixes the error in this
code:
1. name = "Sophie"
2. age = "28"
3. print(name + " is " + age + " years old")
a. No error
b. Missing colon after print(name + “ is “ + age + “ years old”)
c. Incorrect indentation in line 3
d. Convert age to an integer (int(age)) in the print statement
31. Which of the following options correctly fixes the error in this
code:
1. x = 25
2. if x > 20
3. print("x is greater than 20")
a. No error
b. Missing colon after if x > 20
c. Incorrect indentation in line 3
d. Missing parentheses in if x > 20
if 'amir' in names1
print(1)
else:
print(2)
a. if ‘amir’ is names1
b. if ‘amir’ is in names1
c. if ‘amir’ is names1:
d. if ‘amir’ in names1:
33. Which of the following options correctly fixes the error in this
code?
names1 = ['Amir', 'Bala', 'Charlie']
print("names1", )
a. print(my_list)
b. No Error
c. print(names1)
d. print(“names”)
34. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4]
numbers.append([5,6,7,8])
print(length(numbers))
a. print(len(numbers))
b. print(number.len())
c. No Error
d. number.insert([7,8,9])
39. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(number)
a. No error
b. numbers = (1,2,3,4,5)
c. print(numbers)
d. print(num)
40. Which of the following options correctly fixes the error in this
code:
x = 5
while x > 0
print(x)
x -= 1
a. x==1
b. x=+1
c. x= x+1
d. while x>0:
41. Which of the following options correctly fixes the error in this
code:
num1 = 5
num2 = 7
result = num1 + num2
print("The result is: " result)
a. No Error
b. print(“The result is: “,result)
c. print(“The result is: “ + result)
d. both (b) and (c)
42. Which of the following options correctly fixes the error in this
code?
def calculate_sum(a, b):
sum = a + b
return sum
result = calculate_sum(3, 5, 2)
print(result)
a. No error
b. print(“result”)
c. result= calculate_sum(3,5)
d. both (b) and (c)
43. Which of the following options correctly fixes the error in this
code:
marks = {'Math': 90, 'Science': 85, 'English':
88}
if 'History' in marks:
print("History marks:", marks['History'])
else:
print("No record found for History")
a. No error
b. if ‘History’ in marks::
c. else if ::
d. both (b) and (c)
44. Which of the following options correctly fixes the error in this
code:
for i in range(2, 10, 2)
print(i)
a. for i in range(2,10)
b. for i range(2,10)
c. for i range(2,10):
d. for i in range(2,10,2):
46. Which of the following options correctly fixes the error in this
code:
1. x = 7
2. if x % 2 == 0
3. print("Even number")
a. No error
b. Missing colon after ‘if x % 2 == 0ʼ
c. Incorrect indentation in line 3
d. Missing quotes around “Even number”
47. Which of the following options correctly fixes the error in this
code?
1. x = 5
2. if x > 0:
3. print("Positive")
a. No error
b. Incorrect indentation in line 3
c. Missing colon after `if x > 0`
d. Missing quotes around “Positive”
48. Which of the following options correctly fixes the error in this
code:
1. numbers = [1, 2, 3, 4]
2. total = sum(numbers)
3. average = total / len(numbers
4. print("Average:", average)
a. No error
b. Incorrect indentation in line 4
c. Missing closing parenthesis in line 3
d. Missing colon after `print(“Average”, average)`
49. Which of the following options correctly fixes the error in this
code:
1. def subtract(a, b):
2. return a - b
3. result = subtract(5)
a. No error
b. Incorrect number of arguments in line 3
c. Missing colon after `def subtract(a, b)`
d. Missing print statement for result
50. Which of the following options correctly fixes the error in this
code:
1. x = 15
2. if x < 10:
3. print("Less than 10"
print("Done")
a. No error
b. Incorrect indentation in line 3
c. Missing closing parenthesis in line 3
d. Missing quotes around “Less than 10”
51. Which of the following options correctly fixes the error in this
code:
1. x = 100
2. if x = 0:
3. print("Negative Number")
a. x = 100
if x =< 0:
print(“Negative Number”)
b. x = 100
if x => 0:
print(“Negative Number”)
c. x = 100
if x == 0:
print(“Negative Number”)
d. x = 100
if x < 0:
print(“Negative Number”)
52. Which of the following options correctly fixes the error in this
code:
num = input("Enter a number: ")
if num > 0:
print("Positive number")
else:
print("Non-positive number")
a. num = int(input(“Enter a number: “)
if num > 0
print(“Positive number”)
else:
print(“Non-positive number”)
b. num = input(“Enter a number: “)
if num > 0:
print(“Positive number”)
elif:
print(“Non-positive number”)
c. num = int(input(“Enter a number: “))
if num > 0:
print(“Positive number”)
else:
print(“Non-positive number”)
d. num = int(input(“Enter a number: “))
if num > 0
print(“Positive number”)
else:
print(“Non-positive number”)
53. Which of the following options correctly fixes the error in this
code:
def add_numbers(a, b)
result = a + b;
return result
a. def add_numbers(a, b):
result = a + b;
return result;
b. def add_numbers(a b):
result = a + b
return result
c. def add_numbers(a, b)
result = a - b
return result
d. def add_numbers(a, b)
result = a + b
return result
54. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
a. squares = (num ** 2) for num in numbers
b. squares = [num ** 2 for num in numbers]
c. squares = [num ** 2, for num in numbers]
d. squares = (num ** 2, for num in numbers)
55. Which of the following options correctly fixes the error in this
code:
x = 10
if x > 5:
print("Greater than 5")
else if x == 5:
print("Equal to 5")
else:
print("Less than 5")
a. else if x == 5:
print(“Equal to 5”)
b. elif x == 5:
print(“Equal to 5”)
c. else x == 5:
print(“Equal to 5”)
d. elseif x == 5:
print(“Equal to 5”)
56. Which of the following options correctly fixes the error in this
code:
def power(base, exponent=2):
result = base ** exponent
return result
a. def power(base, exponent=2):
result = base ** exponent
return result
b. def power(exponent=2, base):
result = base ** exponent
return result
c. def power(base=2, exponent):
result = base ** exponent
return result
d. def power(exponent, base=2)
result = base ** exponent
return result
57. Which of the following options correctly fixes the error in this
code:
def add_numbers(x, y)
return x + y
a. def add_numbers(x, y):
b. def add_numbers(x, y)
c. def add_numbers(x, y);
d. def add_numbers(x y):
58. Which of the following options correctly fixes the error in this
code:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
if color == "green"
print("Found green!")
a. if color == green:
b. elif color == “green”:
c. if color = “green”:
d. if color == “green”:
59. Which of the following options correctly fixes the error in this
code:
num = 15
if num > 10
print("Num is greater than 10")
else
print("Num is less than or equal to 10")
a. if num > 10:
print((“Num is greater than 10”))
else
print(“Num is less than or equal to 10”)
b. if num > 10
print(“Num is greater than 10”)
else:
print(“Num is less than or equal to 10”)
c. if num > 10:
print(“Num is greater than 10”)
else:
print(“Num is less than or equal to 10”)
d. if num > 10:
print(“Num is greater than 10”)
else:
print(“Num is less than or equal to 10”)
60. Which of the following options correctly fixes the error in this
code:
for i in range(5):
print(i)
a. for i in range(5):
0 print(i)
b. for i in range(5):
print(i)
c. for i is in range(5)
print(i)
d. for i in range(5); print(i)
61. Which of the following options correctly fixes the error in this
code:
x = 10
if x % 2 = 0:
print("Even number")
else:
print("Odd number")
a. if x % 2 == 0:
print(“Even number”)
else:
print(“Odd number”)
b. if x % 2 = 0:
print(“Even number”)
else
print(“Odd number”)
c. if x % 2 == 0:
print(“Even number”)
else:
print(“Odd number”)
d. if x % 2 = 0:
print(“Even number”)
else:
print(“Odd number”)
62. Which of the following options correctly fixes the error in this
code:
total = 0
for i in range(5)
total += i
print(total)
a. for i in range(5):
total += i
print(total)
b. for i in range(5):
total += i
print(total)
c. for i in range(5):
total += i
print(total)
d. for i in range(5): total += i print(total)
63. Which of the following options correctly fixes the error in this
code:
x = 7
y = "8"
result = x + y
a. result = x + int(y)
b. result = x + eval(y)
c. result = string(x) + y
d. Both (a) and (b)
64. Which of the following options correctly fixes the error in this
code:
for color in colors:
print(color)
if color == "green"
print("Found green!")
a. if color == green:
b. if color == “green”:
c. if color = “green”:
d. if color = “green”
65. Which of the following options correctly fixes the error in this
code:
def multiply_numbers(x, y):
return x * y
a. def multiply_numbers(x, y)
return x * y
b. def multiply_numbers(x, y, z):
return x * y
c. def multiply_numbers(x, y):
return x * y;
d. def multiply_numbers(x, y): return x * y * z;
66. Which of the following options correctly fixes the error in this
code:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
if color == "red"
print("Found red!")
a. elif color == “red”:
b. if color == “red”:
c. if color = “red”:
d. if color = “red”
67. Which of the following options correctly fixes the error in this
code:
nums = [1, 2, 3, 4, 5]
cubed_nums = [num ** 3 for num in nums]
print(squared_nums)
a. [cubed_nums = (num ** 3 for num in nums)]
b. cubed_nums = [num ** 3 for num in nums]
c. cubed_nums = {num ** 3 for num in nums}
d. cubed_nums = (num ** 3 for num in nums)
68. Which of the following options correctly fixes the error in this
code:
num = 20
if num > 15
print("Num is greater than 15")
else
print("Num is less than or equal to 15")
a. if num > 15:
print(“Num is greater than 15”)
else:
print(“Num is less than or equal to 15”)
b. if num > 15
print(“Num is greater than 15”)
else
print(“Num is less than or equal to 15”)
c. if num= > 15:
print(“Num is greater than 15”)
else:
print(“Num is less than or equal to 15”)
d. if num > 15:
print(“Num is greater than 15”)
else:
print(“Num is less than or equal to 15”)
69. Which of the following options correctly fixes the error in this
code:
for i in range(7):
print(i)
a. for i in range(7):
print(i);
b. for i in range(7):
print(i)
c. for i in range(7)
print(i);
d. for i range(7): print(i)
70. Which of the following options correctly fixes the error in this
code:
a = 25
b = "94"
result = a + b
a. result = a + int(b)
b. result = eval(a) + b
c. result = string(a) + b
d. result = a ++ b
71. Which of the following options correctly fixes the error in this
code:
a= [1, 2, 3, 4, 5]
for i in range(1, 5):
a[i-1] == a[i]
print(a)
a. for i in range(1, 5):
a[i-1] = a[i]
print(a)
b. for i in range(1, 5):
a[i-1] = a[i]
print(a)
c. for i in range(1, 5):
a[i-1] == a[i]
print(a)
d. for i is in range(1, 5):
a[i-1] = a[i]
print(a)
72. Which of the following options correctly fixes the error in this
code:
Def square(a):
return a * a
a. def square(a):
return a * a
b. def square(a):
return = a * a
c. def square(a): return: a * a
d. def square(x): return a * a
73. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda: x: x ** 2,
numbers))
print(squared_numbers)
a. squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)
b. squared_numbers = map(lambda x: x ** 2, numbers)
print(squared_numbers)
c. squared_numbers = {x ** 2 for x in numbers}
print(squared_numbers)
d. squared_numbers = (x ** 2 for x in numbers)
print(squared_numbers)
74. Which of the following options correctly fixes the error in this
code:
def divide_numbers(x, y):
return x / y
a. def divide_numbers(x):
return x / y
b. def divide_numbers(x, y):
return x / y
c. def divide_numbers(x, y): return: x / y
d. def divide_numbers(x, y): return= x / y
75. Which of the following options correctly fixes the error in this
code:
temperature = 25
if temperature < 0:
print("Freezing")
elif temperature => 0 and temperature <= 20:
print("Cold")
else:
print("Warm")
a. if temperature < 0:
print(“Freezing”)
elif temperature >= 0 and temperature <= 20:
print("Cold")
else:
print("Warm")
a. if temperature < 0:
print(“Freezing”)
elif temperature > 0 and temperature =< 20:
print(“Cold”)
else:
print(“Warm”)
b. if temperature < 0:
print(“Freezing”)
elif temperature >= 0 or temperature <= 20:
print(“Cold”)
else:
print(“Warm”)
c. if temperature < 0:
print(“Freezing”)
elif temperature > 0 and temperature < 20:
print(“Cold”)
else:
print(“Warm”)
76. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4, 5]
sum_numbers = 0
for num in numbers:
sum_numbers += num
print(sum_numbers)
a. sum_numbers = 0
for num in numbers: sum_numbers += numbers
print(sum_numbers)
b. sum_numbers = 0 for num in numbers: sum_numbers += num
print(sum_numbers)
c. sum_numbers = 0
for num in numbers: sum_numbers += num
print(sum_numbers)
d. sum_numbers = 0
for num in numbers:
sum_numbers += num
print(sum_numbers)
77. Which of the following options correctly fixes the error in this
code:
def is_even(x):
if x % 2 = 0
return True
else:
return False
a. def is_even(x):
if x % 2 == 0:
return True
else:
return False
b. def is_even(x):
if x % 2 = 0:
return True
else
return False
c. def is_even(x):
return x % 2 = 0
d. def is_even(x):
return x % 2 == True
78. Which of the following options correctly fixes the error in this
code:
def print_numbers():
for i in range(5):
print(i)
a. def print_numbers():
for i in range(5):
print(i)
b. def print_numbers():
for i in range(5):
print(i)
c. def print_numbers():
for i in range(5): print(i)
d. def print_numbers(): for i range(5): print(i)
79. Which of the following options correctly fixes the error in this
code:
x = 10
if x > 0:
print("Positive")
else if x < 0:
print("Negative")
else:
print("Zero")
a. if x > 0:
print(“Positive”)
else if x < 0:
print(“Negative”)
else:
print(“Zero”)
b. if x > 0:
print(“Positive”)
else if x < 0:
print(“Negative”)
else:
print(“Zero”)
c. if x > 0
print(“Positive”)
elif x < 0:
print(“Negative”)
elif:
print(“Zero”)
d. if x > 0:
print(“Positive”)
elif x < 0:
print(“Negative”)
else:
print(“Zero”)
80. Which of the following options correctly fixes the error in this
code:
numbers = [7, 67, 2, 34, 532]
even_numbers = [num for num is in numbers if
num % 2 == 0]
print(even_numbers)
a. even_numbers = {num for num in numbers if num % 2 == 0}
print(even_numbers)
b. even_numbers = [num for num in numbers if num % 2 = 0]
print(even_numbers)
c. even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
d. even_numbers = (num for num in numbers if num % 2 == 0)
print(even_numbers)
81. Which of the following options correctly fixes the error in this
code:
def power_of_two(n)
return 2 ** n
a. def power_of_two(n):
return 2 ** n
b. def power_of_two(n)
return 2 ** n
c. def power_of_two(n): return = 2 ** n
d. def power_of_two(n):
return 2 ** n
82. Which of the following options correctly fixes the error in this
code:
grades = [90, 85, 88, 92, 95]
average_grade = sum(grades) / len(grades)
print("Average Grade:, average_grade")
a. average_grade = grades.sum() / grades.len()
print(“Average Grade:” , average_grade)
b. average_grade = sum(grades) / len(grades
print(“Average Grade:”, average_grade)
c. average_grade = sum(grades) / len(grades)
rint(Average Grade:, average_grade)
d. average_grade = sum(grades) / len(grades)
print(“Average Grade:”, average_grade)
83. Which of the following options correctly fixes the error in this
code:
L1= ["ram","hello",1,2,3,"hello world",
[1,2,3,4]];
print("L1")
a. No Error c. print(L1)
b. print(L1); d. both (b) and (c)
84. Which one is the right way to access the last element of the list:
L1= ["ram","hello",1,2,3,"hello world",
[1,2,3,4]];
print("L1")
a. Print L1[last index]
b. Print L1 [-1]
c. Print L1 [-LAST INDEX]
d. None of the above
85. Which of the following options correctly fixes the error in this
code:
name = "John"
age = 30
print("Name:", name, "Age:" age)
a. print(“Name:”, name + “Age:”, age)
b. print(“Name:”, name, “Age:”, age
c. print(“Name:” + name + “Age:” + age)
d. print(“Name:”, name, “Age:”, age)
86. Which of the following options correctly fixes the error in this
code:
def cube(b)
return b ** 3
a. def cube(b):
return b ** 3
b. def cube(b)
return b ** 3
c. def cube(b): return: b ** 3
d. def cube(b): return= b ** 3
87. Which of the following options correctly fixes the error in this
code:
colors = ["white", "black", "blue"]
for color in colors:
print(color)
if color == "blue"
print("Found blue!")
a. if color == blue:
b. if color = blue:
c. if color == “blue”:
d. both (a) and (c)
88. Which of the following options correctly fixes the error in this
code:
def add (x, y)
return x + y
a. def add (x, y):
return x + y
b. def add (x, y):
return x + y;
c. def add (x, y):
return x + y
d. both (b) and (c)
89. Which of the following options correctly fixes the error in this
code:
x = 5
while x > 0
print(x)
x -= 1
a. x==1
b. x=+1
c. x= x+1
d. while x>0:
90. Which of the following options correctly fixes the error in this
code:
x = 20
if x % 2 = 0
print("Even number")
else:
print("Odd number")
a. if x % 2 : 0
print(“Even number”)
b. if x % 2 == 0:
print(“Even number”)
c. if x % 2 = 0:
print(“Even number”)
d. if x mod 2 = 0:
print(“Even number”)
91. Which of the following options correctly fixes the error in this
code:
values = [10, 20, 30, 40]
sum = 0
for val in values
sum += val
print(sum)
a. for values in values:
b. for sum in values;
c. for val in values:
d. for i in values:
92. Which of the following options correctly fixes the error in this
code:
age = input("Enter your age:")
if age < 18:
print("You are a minor.")
else:
print("You are an adult.")
a. if int(age) < 18:
print(“You are a minor.”)
b. if age >= 18:
print(“You are an adult.”)
c. elif age < 18:
print(“You are a minor.”)
d. No Error
93. Which of the following options correctly fixes the error in this
code:
score = 85
if score >= 90:
grade = 'A'
else if score >= 80
grade = 'B'
else:
grade = 'C'
a. elif score >= 80:
b. elif score => 80:
c. else score <= 80:
d. No Error
95. Which of the following options correctly fixes the error in this
code:
value = 15
if value > 10:
print("Greater than 10")
else
print("Less than or equal to 10")
a. value = 15
if value > 10:
print(“Greater than 10”)
else:
print(“Less than or equal to 10”)
b. value = 15
if value > 10:
print(“Greater than 10”)
else:
print(“Less than or equal to 10”)
c. value = 15
if value > 10:
print(“Greater than 10”)
else:
print(“Less than or equal to 10”)
d. value = 15
if value > 10:
print(“Greater than 10”)
else:
print(“Less than or equal to 10”)
96. Which of the following options correctly fixes the error in this
code:
numbers = [1, 2, 3, 4]
for num in numbers:
print(num)
if num == 3:
break
a. if num == 3: break
b. if num == 3
break
c. if num == 3:
continue
d. if num == 3 continue
98. Which of the following options correctly fixes the error in this
code:
def factorial(n):
if n == 0 or n == 1
return 1
else:
return n * factorial(n - 1)
a. if n == 0 OR n == 1:
b. if n == 0 | n == 1:
c. if n == 0 or n == 1:
d. both (b) and (c)
99. Which of the following options correctly fixes the error in this
code:
def is_prime(n):
for i in range(2, n):
if n % i = 0:
return False
return True
a. if n mod i == 0:
b. if n % i == 0:
c. if n % i == 0
d. if n % i is 0
100. Which of the following options correctly fixes the error in this
code:
l1=[45,56,22,["hello","everyone"]]
l1.reverse() print(l1)
a. No Error
b. l1=[45,56,22,[“hello”,”everyone”]]
l1.reverse(); print(l1);
c. l1=[45,56,22,[“hello”,”everyone”]]
l1.reverse(); print(l1)
d. both (b) and (c)
101. Which of the following options correctly fixes the error in this
code:
def count_vowels(s):
vowels = aeiou
count = 0
for i in s:
if i in vowels:
count = count + 1
return count
a. No error
b. vowel == aeiou
c. vowel = ‘aeiou’
d. vowels = “aeiou”
102. Which of the following options correctly fixes the error in this
code:
def max(x, y):
if x > y:
return x
elif x < y:
return y
else
return x
print(max(5, 10))
a. def max(x, y):
if x > y
return x
elif x < y:
return y
else:
return x
b. def max(x, y):
if x > y:
return x
elif x < y:
return y
else:
return x
c. def max(x, y):
if x > y:
return x
else if x < y:
return y
else:
return x
d. def max(x, y):
if x > y:
return x
elif x < y:
return y
else:
return x
103. Which of the following options correctly fixes the error in this
code:
def multiply(a, b):
result = a * b
Return result
a. Return a * b
b. return result:
c. return result;
d. No Error
104. Which of the following options correctly fixes the error in this
code:
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or
year % 400 == 0):
return True
else
return False
a. def is_leap_year(year):
if year % 4 == 0 and (year % 100 !== 0 or year % 400 == 0):
return True
else:
return False
b. def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 = 0):
return True
else:
return False
c. def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
d. def is_leap_year(year):
if year % 4 = 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
105. Which of the following options correctly fixes the error in this
code:
def is_substring(s1, s2)
return s1 in s2
print(is_substring("cat", "concatenate")
a. def is_substring(s1, s2):
return s1 is s2:
print(is_substring(“cat”, “concatenate”)
b. def is_substring(s1, s2):
return s1 is s2
print(is_substring(“cat”, “concatenate”)
c. def is_substring(s1, s2):
return s1 in s2:
print(is_substring(“cat”, “concatenate”)
d. def is_substring(s1, s2):
return s1 in s2
print(is_substring(“cat”, “concatenate”)
107. Which of the following options correctly fixes the error in this
code:
L1 = [1,27,986,1783]
Print("276 in L1")
a. L1=[1,27,986,1783]
Print(276 is L1)
b. L1=[1,27,986,1783]
Print(276 is in L1)
c. L1=[1,27,986,1783]
Print(“276 is L1”)
d. L1=[1,27,986,1783]
Print(276 in L1)
108. Which of the following options correctly fixes the error in this
code:
L1=[10,100,1000,10000]
print(L1) * 2
a. No Error
b. print(L1 * 2)
c. print(“L1 * 2”)
d. both (b) and (c)
109. Which of the following options correctly fixes the error in this
code:
amount = 50.0
if amount > 30
print("High value")
else:
print("Low value")
a. amount = 50.0
if amount > 30:
print(“High value”)
else:
print(“Low value”)
b. amount = 50.0
if amount > 30:
print(“High value”)
else:
print(“Low value”)
c. amount = 50.0
if amount > 30:
print(“High value”)
else:
print(“Low value”)
d. amount == 50.0
if amount > 30:
print(“High value”)
else:
print(“Low value”)
110. Which of the following options correctly fixes the error in this
code:
def calculate_area("radius"):
area = 3.14 * radius ** 2
return area
a. def calculate_area(radius)
area = 3.14 * radius ** 2
return area
b. def calculate_area(radius):
area = 3.14 * radius ** 2
return area
c. def calculate_area(radius):
area = 3.14 * radius ** 2
return area;
d. No Error
111. Which of the following options correctly fixes the error in this
code:
value = 7
if value < 10:
print("Single-digit number")
else:
print("Double-digit number"
a. if value < 10:
print(“Single-digit number”)
else:
print(“Double-digit number”)
b. if value < 10:
print(“Single-digit number”)
else:
print(“Double-digit number”)
c. if value < 10:
print(“Single-digit number”)
else:
print(“Double-digit number”
d. if value < 10:
print(“Single-digit number”)
else:
print(“Double-digit number”)
112. Which of the following options correctly fixes the error in this
code:
x = 15
y = "5"
result = x - y
a. result = x - int(y)
b. result = x - eval(y)
c. result = str(x) - y
d. both (a) and (b)
114. Which of the following options correctly fixes the error in this
code:
def find_average(numbers)
average = sum(numbers) / len(numbers)
return average
a. def find_average(numbers):
average = sum(numbers) / len(numbers)
return average
b. def find_average(numbers):
average = sum(numbers) / len(numbers)
return average
c. def find_average(numbers):
average = sum(numbers) / len(numbers);
return average
d. def find_average(numbers):
average = sum(numbers) / len(numbers)
return average;
115. Which of the following options correctly fixes the error in this
code:
temperature = 25
if temperature > 30:
print("Hot")
else
print("Not hot")
a. if temperature > 30:
print(“Hot”)
else:
print(“Not hot”);
b. if temperature >= 30:
print(“Hot”)
else:
print(“Not hot”)
c. if temperature > 30
print(“Not hot”)
else:
print(“Hot”)
d. if temperature < 30:
print(“Hot”)
else:
print(“Not hot”)
118. Which of the following options correctly fixes the error in this
code:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
if name = "Bob"
print("Found Bob!")
a. if name == “Bob”:
b. if name = Bob:
c. if name = “Bob”:
d. if name == “Bob”
119. Which of the following options correctly fixes the error in this
code:
values = [1, 2, 3, 4]
for val in values:
if val % 2 = 0
print(f"{val} is even.")
else:
print(f"{val} is odd.")
a. if val % 2 == 0
b. if val % 2 ==> 0;
c. if val % 2 == 0:
d. if val % 2 === 0:
120. Which of the following options correctly fixes the error in this
code:
def calculate_discount(price):
if price > 100:
discount = 0.1
else if price => 50:
discount = 0.05
else:
discount = 0
return price * discount
a. elif price > 50: discount = 0.05
b. elif price => 50: discount = 0.05;
c. elif price >= 50: discount = 0.05:
d. elif price >= 50: discount = 0.05;
121. Which of the following options correctly fixes the error in this
code:
x = 10
if x > 5:
print("Greater than 5")
else if x == 5:
print("Equal to 5")
else:
print("Less than 5")
a. else if x == 5:
print(“Equal to 5”)
b. elif x == 5:
print(“Equal to 5”)
c. else x == 5:
print(“Equal to 5”)
d. elseif x = 5:
print(“Equal to 5”)
123. Which of the following options correctly fixes the error in this
code:
colors = ['cyan', 'violet', 'indigo']
for color in colors:
print(color)
if color == 'cyan'
print('Found green!')
a. No Error
b. if color == cyan:
print(‘Found cyan!’)
c. if color = ‘cyan’ :
print(‘Found cyan!’)
d. Both (b) and c)
124. Which of the following options correctly fixes the error in this
code:
temperature = 25
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Moderate")
else
print("Cold")
a. temperature = 25
if temperature > 30:
print(“Hot”)
elif temperature > 20:
print(“Moderate”)
else:
print(“Cold”)
b. temperature = 25
if temperature > 30:
print(“Hot”)
elif temperature > 20:
print(“Moderate”)
else:
print(“Cold”)
c. temperature = 25
if temperature > 30:
print(“Hot”)
elif temperature > 20:
print(“Moderate”)
else:
print(“Cold”)
d. temperature = 25
if temperature > 30:
print(“Hot”)
elif temperature > 20:
print(“Moderate”)
else:
print(“Cold”)
125. Which of the following options correctly fixes the error in this
code:
x= ['Today','Tomorrow','Yesterday']
print(x):
a. No Error
b. printf(x)
c. print(x)
d. both (b) and (c)
126. Which of the following options correctly fixes the error in this
code:
x=[25,35,45]
print(x(0))
a. No Error
b. print(x[0])
c. print(x{0})
d. both (b) and (c)
127. Which of the following options correctly fixes the error in this
code:
x=[10,20,30]
print("x[1]+x[2]")
a. No Error
b. print(“x[1]” + “x[2]”)
c. print(x[1] + x[2])
d. both b) and c)
128. Which of the following options correctly fixes the error in this
code:
x=['Sunday','Monday','Tuesday']
y=x[1] + x[2]
print("y")
a. No Error
b. print(y)
c. print(y);
d. both (b) and (c)
130. Which of the following options correctly fixes the error in this
code:
if x == "happy":
print("hola")
else: print("Au Revoir")
a. if x == “happy”:
print(“hola”)
else:
print(“Au Revoir”)
b. if x = “happy”:
print(“hola”)
else:
print(“Au Revoir”)
c. if x == “happy”:
print(“hola”)
else: print(“Au Revoir”)
d. if x == “happy”:
print(“hola”)
else
print(“Au Revoir”)
131. Which of the following options correctly fixes the error in this
code:
def plus (x,y):
x=x+1 and y=y+1
return(x,y)
print(plus(1,2))
a. No Error
b. def plus (x,y):
x=x+1 , y=y+1
return(x,y)
c. def plus (x,y):
x=x+1 ; y=y+1
return(x,y)
d. both (b) and (c)
132. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2]
print(x.list())
a. No Error
b. print(x)
c. print(list(x))
d. both (b) and (c)
133. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2]
x.add(1)
print(x)
a. No Error
b. x.extend(1)
c. x.append(1)
d. both (b) and (c)
134. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2]
x.insert(1,0)
print(x)
a. No Error
b. x.append(1,0)
c. x.extend(1,0)
d. both (b) and (c)
135. Which of the following options correctly fixes the error in this
code:
x=["hi", "cry", "bye"]
x.delete(2)
print(x)
a. No Error
b. x.del(2)
c. x.pop(2)
d. both b) and c)
136. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2,1]
x.reversed_list()
a. x.reverse()
b. x.sort(reverse = True)
c. x.sort(reverse == True)
d. Both (a) and (b)
137. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2,1]
print(x.indexof(1)
a. No Error
b. print(x.index(1)
c. print(x.indexof(1))
d. print(x.index(1))
138. Which of the following options correctly fixes the error in this
code:
l1=[45,56,2,["hi","everyone"]]
l1.reversed()
print(l1)
a. l1.sort(reverse = “true”)
b. l1.sort(reverse = true)
c. l1.reverse()
d. both (b) and (c)
139. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2,,1]
x.extend(x)
print(x)
a. x = [5,4,3,2,1]
b. x = (5,4,3,2,1)
c. x = {5,4,3,2,1}
d. All of the Above
141. Which of the following options correctly fixes the error in this
code?
def power(x, n)
result = x ** n
return result
print(power(2, 3))
a. No Error
b. def power(x, n):
result = x ** n
return result
c. def power(x, n):
result = x ** n;
return result
d. def power x, n:
result = x ** n
return result
144. Which of the following options correctly fixes the error in this
code:
def square(x)
result = x * x
print(result)
a. def square(x):
print(x * x)
b. def square(x):
result = x ** 2
print(result)
c. def square(x):
result = x * x
print(result)
d. All of the above
146. Which of the following options correctly fixes the error in this
code:
def divide(a, b):
if b != 0:
result = a / b
return result
else:
return "Error: Division by zero"
a. No Error
b. return a / b if b != 0 else “Error: Division by zero”
c. if b = 0:
return “Error: Division by zero”
else:
result = a / b
return result
d. Both (a) and (b)
147. Which of the following options correctly fixes the error in this
code:
def greet(name):
print("Hello, " name "!")
a. No Error
b. print(“Hello, “ + name + “!”)
c. print(“Hello, “ , name + “!”)
d. both (b) and (c)
148. Which of the following options correctly fixes the error in this
code:
for i in range(3):
for j in range(3):
print(i, j)
a. No Error
b. for i in range(3):
for j in range(3):
print(i, j)
c. for i in range(3):
for j in range(3):
print(i, j)
d. for i in range(3):
for j in range(3):
print(i, j)
149. Which of the following options correctly fixes the error in this
code:
x=[25,35,53,25,52,35,25]
del x[3]
print(x)
a. No Error
b. del.x[3]
c. delete(x[3])
d. x.del(3)
152. Which of the following options correctly fixes the error in this
code:
marks = 85
if marks >= 90:
grade = "A"
else if marks >= 80 and marks < 90
grade = "B"
else:
grade = "C"
a. elif marks >= 80 and marks < 90:
grade = “B”
b. elif marks >= 80 & marks < 90:
grade = “B”
c. elif marks => 80 and marks < 90:
grade = “B”
d. Both (a) and (b)
154. Which of the following options correctly fixes the error in this
code:
x=[4,0,7]
y= (x[0]) + (x[1]
print(y)
a. No Error
b. y = {x[0]} + {x[1]}
c. y = x[0] + x[1]
d. both (b) and (c)
155. Which of the following options correctly fixes the error in this
code:
x=[4,0,7]
Y=float([0]+x[2])
print(y)
a. No Error c. print(Y)
b. print(y) d. print(y);
156. Which of the following options correctly fixes the error in this
code:
x=[24,50,37]
y=24 is x
print(y)
a. No Error c. y = 24 in x
b. y = 24 is in x d. both (b) and (c)
157. Which of the following options correctly fixes the error in this
code:
x='Python'
y= 'y' in x
print(y)
a. No Error c. y = “y” is in x
b. y = y in x d. y = “y” is x
158. Which of the following options correctly fixes the error in this
code:
x='Python'
Print(x[4])
a. No Error c. print(x[4])
b. print(x(4)) d. Print(x[4]);
159. Which of the following options correctly fixes the error in this
code:
x='Python'
print(x(2:4))
a. No Error c. print(x(2:4));
b. print(x{2:4}) d. print(x[2:4])
160. Which of the following options correctly fixes the error in this
code:
x= 'Python'
Print(x[:])
a. No Error c. print(x[])
b. print(x[:]) d. both (b) and (c)
161. Identify the error in the following code:
def find_max(a, b, c):
if a > b and a > c:
return a
elif b > a and b > c
return b
else:
return c
a. No Error
b. if a > b and a > c:
return b
c. elif b > a & b > c:
return a
d. else if b > a and b > c:
return a
162. Which of the following options correctly fixes the error in this
code?
a=[4,7,9]
b=[4,7,9]
print(a = b)
a. No Error
b. print(a is b)
c. print( a==b)
d. both (b) and (c)
164. Which of the following options correctly fixes the error in this
code:
def display_info(name, age):
print("Name:", name)
print("Age:", age)
display_info("Anirudh")
a. display_info(“Anirudh”, 25, “Female”)
b. display_info(name=”Alice”)
c. display_info(“Anirudh”, age=25)
d. None of the Above
165. Which of the following options correctly fixes the error in this
code:
a=[4,25,16,9,24]
print(max in (a))
a. print(max_value in (a))
b. print(max in a)
c. print(max in (a))
d. print(max(a))
166. Which of the following options correctly fixes the error in this
code:
x=[5,4,3,2,1]
x.clear():
print(x)
a. No Error
b. x.clear():
print(x)
c. x.clear()
print(x)
d. x.clear()
print(x)
167. Which of the following options correctly fixes the error in this
code:
x=(5,4,3,2,1)
y=x.copy()
print(y)
a. No Error
b. y = copy(x)
c. y = list(copy(x))
d. y = list(x).copy()
168. Which of the following options correctly fixes the error in this
code:
x=[Null list ]
For I in range(10):
x.append(i**2)
print(x)
a. No Error c. x = [NULL]
b. x = [ ] d. x = [Null]
169. Which of the following options correctly fixes the error in this
code:
x=list(map (lambda x:x**2,range(5))
print(x)
a. x=list(map(lambda x:x**2,range(5)))
b. x=list(map[lambda x:x**2,range(5)])
c. x=list(map (lambda x:x**2: range(5)))
d. No Error
170. Which of the following options correctly fixes the error in this
code:
x=[i**2 for I in range(4)]
print(x)
a. No Error
b. x=[I**2 for I in range(4)]
c. x=[i**2 for i in range(4)]
d. Both (b) and (c)
171. Which of the following options correctly fixes the error in this
code:
a = ( 1,2,3,4,45,78}
print(a)
a. No Error
b. a = (1,2,3,4,45,78]
c. a = (1,2,3,4,45,78)
d. both (b) and (c)
172. Which of the following options correctly fixes the error in this
code:
a=[ ]
for x in [0,1,2]:
for y in [3,4,5]:
if x!== y:
a .append( ((x, y) )
print(a)
a. No Error c. if x is not y:
b. if x!= y: d. both (b) and (c)
173. Which of the following options correctly fixes the error in this
code:
a=[-2, -1, 0,1,2]
print(typeof(a)
a. No Error
b. print(typeof(a))
c. print(classof(a))
d. print(type(a))
174. Which of the following options correctly fixes the error in this
code:
a=[-3, -1,0,1,3]
print(min(a)
a. No Error
b. print(minimum in a)
c. print(min(a))
d. print(MIN(a))
175. Which of the following options correctly fixes the error in this
code:
x = 5
y = 7
result = x + y
print("The sum is: " result)
a. No Error
b. print( “The sum is:” ,result)
c. print(“The sum is:” + result)
d. both (b) and (c)
176. Which of the following options correctly fixes the error in this
code:
def calculator(a, b):
addition = a + b
return addition
result = calculator(3, 5, 2)
print(result)
a. No error
b. print(“result”)
c. result= calculator(3,5)
d. addition = a+b+c
177. Which of the following options correctly fixes the error in this
code:
scores = {'Dance': 34, 'Games': 99, 'Singing':
91}
if 'Math' in scores
print("Math score:", score['Math'])
else:
print("No record found for Math")
a. No error
b. if ‘Math’ is in scores:
c. if Math in scores:
d. if ‘Math’ in scores:
178. Which of the following options correctly fixes the error in this
code:
for i is in range(1, 12, 3)
print(i)
a. No Error
b. for i is range(1,12,3):
c. for i range(1,12):
d. for i in range(1,12,3):
180. Which of the following options correctly fixes the error in this
code:
x = 23
if x % 2 !== 0
print("Odd number")
a. No error
b. if X % 2!= 0:
c. if x%2 !== 0:
d. if x%2 != 0:
181. Which of the following options correctly fixes the error in this
code:
x = 345
if x > 0:
print("Affirmative")
a. No error c. if x=> 0:
b. if X > 0: d. if x > 0
182. Which of the following options correctly fixes the error in this
code:
1. numbers = [12, 52, 32, 47,65]
2. total = sumof(numbers)
3. average = total / len(numbers)
4. print("Average:", average)
a. No error
b. total = sum(numbers)
c. average = total / numbers.len()
d. both b) and c)
183. Which of the following options correctly fixes the error in this
code:
function subtract(a, b):
return a - b
result = subtract(5)
a. No Error
b. func subtract(a,b)
c. def subtract(a,b):
d. def subtract(a,b);
184. Which of the following options correctly fixes the error in this
code:
x = 20
if x < 80:
print("Less than 80"
print("Done")
a. No error
b. print(Less than 80)
c. print( > 80)
d. print(“Less than 80”)
185. Which of the following options correctly fixes the error in this
code:
a= [-3, -1,0,1,3]:
print(a)
a. a= [-3, -1,0,1,3]:
print(a)
b. A = list([-3, -1,0,1,3])
print(a)
c. a= [-3, -1,0,1,3]
print(a)
d. list(a) = [-3, -1,0,1,3]
print(a)
192. Which of the following options correctly fixes the error in this
code:
def find_gcd(a, b):
while b:
a, b = b, a % b
return a
print(find_gcd(12, 18))
a. No Error
b. return a % b
c. while a:
d. while b !== 0:
196. Which of the following options correctly fixes the error in this
code?
def find_max(lst):
return lst.max()
a. No Error
b. return max_element(lst)
c. return max(lst)
d. return lst.maximum()
198. Which of the following options correctly fixes the error in this
code:
def is_valid_email(email):
return email.contains('@') and
email.contains('.')
a. No Error
b. return ‘@’ in email and ‘.’ in email
c. return email.count(‘@’) == 1 and email.count(‘.’) == 1
d. Both (b) and (c)
199. Which of the following options correctly fixes the error in this
code:
def find_hypotenuse(a, b):
return (a ** 2 + b ** 2) ** 2
a. return a * a + b * b
b. return (a * a + b * b) ** 0.5
c. return a * b
d. No Error
200. Which of the following options correctly fixes the error in this
code:
def check_divisibility(num, divisor):
return num % divisor == 0
a. No Error
b. return num * divisor == 0
c. return num / divisor == 0
d. return num % divisor != 0
201. Which of the following options correctly fixes the error in this
code:
def find_smallest(lst):
return lst.min()
a. No Error
b. return min(lst)
c. return lst[0]
d. return min_element(lst)
202. Which of the following options correctly fixes the error in this
code:
def remove_punctuation(sentence):
punctuation = '''!()-[]{};:'"\,<>./?
@#$%^&*_~'''
clean_sentence = ""
for char in sentence:
if char not in punctuation:
clean_sentence += char
return clean_sentence
a. No Error
b. if char == punctuation:
c. if char == punctuation:
d. if char not in punctuation:
203. Which of the following options correctly fixes the error in this
code:
def find_quotient(dividend, divisor):
return dividend \ divisor
a. No Error
b. return dividend // divisor
c. return dividend * divisor
d. return dividend % divisor
204. Which of the following options correctly fixes the error in this
code:
def find_length(s):
return s.len()
a. No Error
b. return s.length()
c. return s.count()
d. return len(s)
205. Which of the following options correctly fixes the error in this
code:
def find_volume(length, width, height):
return: length * width * height
a. No Error
b. return length * width / height
c. return (length * width * height)
d. return length / width * height
206. Which of the following options correctly fixes the error in this
code:
def check_square(n):
if n > 0:
return int(n**0.5) = n**0.5
else:
return False
print(check_square(9))
a. No Error
b. return int(n**0.5) == n
c. return int(n**0.5) == n**0.5
d. return n ** 0.5 == 0
207. Which of the following options correctly fixes the error in this
code:
def print_factors(n):
factors = []
for i in range(1, n+1)
if n % i == 0:
factors.append(i)
return factors
print(print_factors(12))
a. No Error
b. for i in range(1, n):
c. for i in range(1, n+1):
d. for i in range(n):
208. Which of the following options correctly fixes the error in this
code:
def check_anagram(s1, s2):
return sorted(s1) = sorted(s2)
print(check_anagram("listen", "silent"))
a. No Error
b. return sorted(s1) == sorted(s2)
c. return sort(s1) == sort(s2)
d. return sorted(s1) is (sorted(s2))
209. Which of the following options correctly fixes the error in this
code:
def count_vowels(word):
count = 0
vowels = ['a', 'e', 'i', 'o', 'u']
for char in word:
if char in vowels
count += 1
return count
a. No Error
b. if char in vowels:
count += 1
c. if char in vowels:
count += 1
d. elif char in vowels:
count += 1
212. Which of the following options correctly fixes the error in this
code:
def maximum_val(a, b):
if a > b:
return a
elif a < b:
return b
else
return a
print(maximum_val(5, 10))
a. def maximum_val(a, b):
if a > b:
return a
elif a < b:
return b
else:
return a
b. def maximum_val(a, b):
if a > b:
return a
elif a < b:
return b
else:
return a
c. def maximum_val(a, b):
if a > b:
return a
else if a < b:
return b
else:
return a
d. No Error
213. Which of the following options fixes the error in this code:
def multiply(a, b):
V = a * b
Return V
a. Return a ** b c. return V;
b. return V: d. No Error
214. Which of the following options fixes the error in this code:
def leap(year):
if year % 4 == 0 and (year % 100 != 0 or
year % 400 == 0):
return True
else
return False
a. def leap(year):
if year % 4 == 0 and (year % 100 !== 0 or year % 400 == 0):
return True
else:
return False
b. def leap(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 = 0):
return True
else:
return False
c. def leap(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
d. def leap(year):
if year % 4 = 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
215. Which of the following options fixes the error in this code:
def substring(s1, s2)
return s1 in s2
print(substring("eat", "treat")
a. def substring(s1, s2):
return s1 is s2:
print(substring(“eat”, “treat”)
b. def substring(s1, s2):
return s1 is s2
print(substring(“eat”, “treat”)
c. def substring(s1, s2):
return s1 in s2:
print(substring(“eat”, “treat”)
d. def substring(s1, s2):
return s1 in s2
print(substring(“eat”, “treat”)
216. Choose the corrected version of the code below:
def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
return True
else:
return False
print(is_triangle(3, 4, 5))
a. No Error
b. if a + b > c and a + c > b and b + c > = a:
c. if a + b > c or a + c > b or b + c > a:
d. if a + b > c and a + c > b and b + c > a
217. Which of the following options fixes the error in this code?
List1 = [123,42,12,42,1,645,65,5]
Print("27 in L1")
a. Print(27 is List1)
b. Print(27 is in List1)
c. Print(“27 is L1”)
d. Print(27 in List1)
218. Which of the following options fixes the error in this code:
my_list=[32,12,46,74,85,35,3]
print(my_list) * 2
a. No Error
b. print(my_list * 2)
c. print(“my_list * 2”)
d. both (b) and (c)
219. Which of the following options fixes the error in this code:
price = 9999
if price > 4999
print("expensive")
else:
print("Value for Money")
a. No Error
b. if amount > 4999;
c. if amount => 4999:
d. if amount > 4999:
220. Which of the following options fixes the error in this code:
def calculate_perimeter("radius"):
circumference = 2 * 3.14 * radius
return circumference
a. No Error
b. def calculate_perimeter(radius)
c. def calculate_perimeter(radius):
d. def calculate_perimeter(r):
221. Which of the following options fixes the error in this code:
value = 73
if value < 100:
print("Double-digit number")
else:
print("Triple-digit number"
a. No Error
b. print(Triple-digit number)
c. print<<” Triple-digit number”
d. print(“Triple-digit number”)
222. Which of the following options fixes the error in this code:
num1 = 62
num2 = "45"
result = x - y
a. result = num1 - int(num2)
b. result = eval(num1) - num2
c. result = str(num1) – num2
d. Both (a) and (b)
224. Which of the following options fixes the error in this code:
temperature == 25
if temperature > 30:
print("Humid")
else:
print("Moderate")
a. No Error
b. temperature = 25:
c. temperature = 25
d. temperature == 25:
227. Which of the following options fixes the error in this code:
names = ["Cypher", "Sova", "Gekko"]
for name in names:
print(name)
if name = "Raze"
print("Found Raze!")
a. if name == “Raze”:
b. if name = Raze:
c. if name = “ Raze”:
d. if name == “Raze”
228. Which of the following options fixes the error in this code:
lst = [21,3,41,51,2,4,53,12]
for n in lst:
if n % 2 = 0
print(f"{n} is even.")
else:
print(f"{nl} is odd.")
a. if n % 2 == 0 c. if n % 2 == 0:
b. if n % 2 ==> 0; d. if n % 2 === 0:
229. Which of the following options fixes the error in this code:
def calculate_off(sp):
if sp > 599:
discount = 10
else if sp => 299
discount = 5
else:
discount = 0
return price * discount
a. elif sp => 299:
discount = 5
b. else if sp => 299:
discount = 5
c. else if sp >= 299:
discount = 5
d. No Error
230. Which of the following options fixes the error in this code:
x = 23
if x > 100:
print("Greater than 100")
elif x == 100:
print("Equal to 100")
else:
print("Less than 100")
a. else if x = 100:
print(“Equal to 100”)
b. elif x = 100:
print(“Equal to 100”)
c. else x == 100:
print(“Equal to 100”)
d. No Error
232. Which of the following options fixes the error in this code:
balloons = ['green', 'blue', 'red']
for x in balloons:
if x == 'yellow'
print('Found yellow!')
a. No Error
b. if x == yellow:
print(‘Found yellow!’)
c. if x == ‘yellow’ :
print(‘Found yellow!’)
d. Both (b) and (c)
233. Which of the following options fixes the error in this code:
x= ['whenever','forever','clever']
print(x):
a. No Error c. print(x)
b. printf(x) d. both (b) and (c)
234. Which of the following options fixes the error in this code:
L=[32,15,45,34,1,23,12]
print(L(1))
a. No Error c. print(L{1})
b. print(L[1]) d. both (b) and (c)
235. Which of the following options fixes the error in this code:
a=[6,54,543,54]
print("a[1]+a[2]")
a. No Error
b. print(“a[1]” + “a[2]”)
c. print(a[1] + a[2])
d. both (b) and (c)
236. Which of the following options fixes the error in this code:
A=['today','everyday','yesterday']
B=A[0] + A[2]
print("B")
a. No Error c. print(B);
b. print(B) d. both (b) and (c)
237. What will be the output of the following code:
x=[13,12,34,52,81]
x.include(64,375,28)
print(x)
a. No Error
b. x.extend([6,7,8])
c. x.append(6,7,8)
d. both (b) and (c)
238. Which of the following options fixes the error in this code:
m=[23,10,43]
n= (m[0]) + (m[1]
print(n)
a. No Error
b. n = {m[0]} + {m[1]}
c. n = m[0] + m[1]
d. both (b) and (c)
239. Which of the following options fixes the error in this code:
x=[4,0,7]
Y=float([0]+x[2])
Print(y)
a. No Error c. print(Y)
b. print(y) d. print(y);
240. Which of the following options fixes the error in this code:
x=[14, 34,42]
y=99 is x
print(y)
a. No Error c. y = 99 in x
b. y = 99 is in x d. both (b) and (c)
241. Which of the following options fixes the error in this code:
x='bicycle'
y= 'y' in x
print(y)
a. No Error c. y = “y” is in x
b. z = y in x d. y = “y” is x
242. Which of the following options fixes the error in this code:
p ='Valorant'
Print(x[2])
a. No Error c. print(p[2])
b. print(p(2)) d. Print(p[2]);
243. Which of the following options fixes the error in this code:
x= 'Champion'
print(x(2:4))
a. No Error c. print(x(2:4));
b. print(x{2:4}) d. print(x[2:4])
244. Which of the following options fixes the error in this code:
st = 'Duelist'
Print(x[:])
a. No Error c. print(st [])
b. print(s [:]) d. both (b) and (c)
245. Identify the error in the following code:
def find_max(x, y, z):
if x > y and x > z:
return x
elif y > x and y > z
return y
else:
return z
a. No Error
b. elif y > x and y > z:
return y
c. elif y > x & y > z:
return y
d. both (b) and (c)
246. Which of the following options fixes the error in this code:
a=[32,44,22]
b=[32,44,22]
print(a = b)
a. No Error c. print( a==b)
b. print(a is b) d. both (b) and (c)
247. Which of the following options fixes the error in this code:
lst = [32,1,43,53,100,54,99,86]
print(max in (lst))
a. print(max_value in (lst))
b. print(max in lst)
c. print(lst.max())
d. print(max(lst))
248. Which of the following options fixes the error in this code:
y=["as", "in", "is" , "it]
y.clear():
print(x)
a. No Error
b. y.clear():
print(x)
c. y.clear()
print(x)
d. y.clear()
print(x)
249. Which of the following options fixes the error in this code:
list1 = [10,20,30,10,40,10]
print(list1.index[10])
a. No Error
b. print(list1.index(10))
c. print(list1.list_index(10))
d. print(list1.indexof(10))
250. Which of the following options fixes the error in this code:
names = ["Hasan", "Balwant", 'Sean', 'Dia']
print(names[-1][-1])
a. No Error
b. print(names(-1)(-1))
c. print(names[(-1) , (-1)]
d. both (b) and (c)
Conclusion
In conclusion, this chapter has provided a valuable and immersive
exploration into the intricate world of identifying and resolving errors in
Python code. The chapter’s structured approach, covering syntax, runtime,
and logical errors, aims to equip readers with a holistic understanding of
potential challenges encountered during the coding process. As readers
navigate the intricacies of troubleshooting, they are refining their ability to
find errors and cultivating a resilient problem-solving mindset. This chapter
is an essential resource for developers at all levels, reinforcing the importance
of error awareness and offering a roadmap for continuous improvement in
Python programming proficiency. By embracing the lessons learned from this
chapter, readers are better prepared to write robust, error-free code and
confidently navigate the complexities of software development.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
Introduction
As data plays a pivotal role in modern software systems, effectively
interacting with databases is paramount. Python, with its simplicity,
versatility, and vast ecosystem of libraries, emerges as a powerful tool for
database programming. Whether you are a seasoned developer or a
newcomer to Python, this chapter will guide you through the fundamentals of
database programming, providing practical insights, hands-on examples, and
best practices. From connecting to various database systems to executing
queries, managing transactions, and handling data effectively, you will gain
the knowledge and skills needed to harness the full potential of Python in the
realm of databases.
Objectives
The primary objectives of this chapter on Database Programming with
Python are to equip readers with the essential skills and knowledge required
to interact proficiently with databases using the Python programming
language. We aim to provide a comprehensive understanding of database
concepts and how Python serves as an effective tool for seamless integration
and interaction with diverse database systems. By the end of this chapter,
readers will have gained proficiency in establishing connections to databases,
executing queries, and managing data effectively.
2. What is the purpose of the SQL SELECT state To insert data into
a database table
a. To update existing data in a database table
b. To retrieve data from a database table
c. To delete data from a database table
52. In Python, which method is used to fetch the next row from a
result set in a database query?
a. fetchrow()
b. fetchnext()
c. fetchone()
d. None of the above
65. Which method is used to fetch all rows of a MySQL query result?
a. fetch_one() c. fetch_row()
b. fetch_all() d. fetch_many()
66. How can you retrieve the last inserted row ID in MySQL using
pymysql?
a. connection.last_row_id()
b. cursor.last_id()
c. cursor.lastrowid
d. cursor.last_insert_id()
69. Which data type can be used to store text of variable length in
MySQL?
a. TEXT c. CHAR
b. VARCHAR d. STRING
70. How can we update existing rows in a MySQL table using
pymysql?
a. update_row()
b. alter_row()
c. modify_row()
d. UPDATE table SET column=value WHERE condition
75. How can you handle errors while executing MySQL queries in
Python using pymysql?
a. try-except block
b. if-else statement
c. assert statement
d. raise keyword
76. What is the default port for MySQL connections in Python using
pymysql?
a. 3306 c. 5432
b. 8080 d. 27017
77. What method is used to establish a connection to a MySQL
database using pymysql?
a. connect()
b. open()
c. start()
d. connect_to_database()
79. How can you create a new database in MySQL using pymysql?
a. CREATE DATABASE database_name
b. USE database_name
c. ADD DATABASE database_name
d. NEW DATABASE database_name
91. How can you insert multiple rows into a MySQL table using
pymysql?
a. insert_many()
b. add_rows()
c. executemany()
d. batch_insert()
94. How can we retrieve the number of affected rows after executing a
MySQL query using pymysql?
a. cursor.rowcount
b. cursor.get_affected_rows()
c. cursor.affected_rows()
d. cursor.row_count()
99. Which SQL function is used to find the average value in a column
in MySQL?
a. COUNT() c. AVG()
b. SUM() d. MAX()
100. How can you create a new user in MySQL using pymysql?
a. CREATE USER ‘username’@’hostname’ IDENTIFIED BY
‘password’
b. ADD USER ‘username’@’hostname’ PASSWORD ‘password’
c. INSERT USER ‘username’@’hostname’ VALUES (‘password’)
d. REGISTER USER ‘username’@’hostname’ WITH PASSWORD
‘password’
112. What is the primary library used to connect Python with an SQL
database?
a. SQLAlchemy
b. psycopg2
c. pyodbc
d. pandas
120. What is the typical format for a connection string when connecting
to an SQL database in Python?
a. jdbc://user:password@hostname:port/dbname
b. sql://user:password@hostname:db
c. sql://username:password@hostname:port/dbname
d. jdbc://user:password@hostname:db
129. How can you retrieve the results of an SQL query as a pandas
DataFrame in Python?
a. Write the results to a CSV file and then read it into a DataFrame
b. Use the pd.read_sql_query() function
c. Use the db.to_dataframe() method
d. Convert the results to JSON format and then parse it into a
DataFrame
134. How can you retrieve only a specific number of rows from an SQL
query in Python?
a. Use the LIMIT clause in the SQL query
b. Use the SELECT TOP clause in the SQL query
c. Use the fetchone() method
d. Use the fetchmany() method
140. How can we use Python’s fetchone() method to retrieve the first
row of an SQL query result?
a. cursor.fetchone()
b. fetchone(cursor)
c. cursor.fetchone()
d. fetchone(cursor.execute())
142. How can you check if a database table exists in Python before
executing an SQL query?
a. Write a query to check for the table’s existence
b. Use the cursor.execute() method
c. Use the exists_table() method
d. Use the INFORMATION_SCHEMA table
151. How can you execute a stored procedure in an SQL database using
Python?
a. Call the procedure directly using the cursor.execute() method
b. Use the CREATE PROCEDURE statement in SQL
c. Define the procedure in Python code and execute it
d. Use the CALL statement in SQL
157. How can you retrieve metadata about a database table in Python
when connected to an SQL database?
a. Use the cursor.execute() method to query the table
b. Use the cursor.description attribute
c. Use the show() method
d. Use the fetchmetadata() method
159. How can you use a context manager in Python to close a database
connection automatically after executing SQL queries?
a. Use the with statement to create a context manager
b. Manually call the close() method on the connection object
c. Import the contextlib module and use the contextlib.close()
method
d. Use a try-finally block to close the connection
160. How can you retrieve the number of rows affected by an SQL
query in Python?
a. Use the rowcount attribute of the cursor object
b. Use the fetch_count() method
c. Use the count() method
d. Use the SELECT COUNT(*) statement in SQL
168. How do you fetch all rows from a table in an SQLite database
using Python?
a. cursor.execute(“SELECT * FROM table”)
b. cursor.fetchall()
c. cursor.fetch_all()
d. connection.query(“SELECT * FROM table”)
177. How do you handle errors when working with SQLite in Python?
a. Use try-except blocks
b. Use if-else statements
c. Use assert statements
d. Use while loops
187. How do you fetch rows from an SQLite table in chunks in Python?
a. Use the limit and offset clauses in the SELECT statement
b. Use the fetch_chunk() method
c. Use the fetchmany() method with the batch size
d. Use the FETCH_CHUNK command
189. How do you retrieve the last row inserted into an SQLite table
using Python?
a. Use the LAST_INSERT_ROWID() function
b. Use the fetchone() method
c. Use the last_row_inserted() function
d. Use the last_inserted_row() method
207. How do you retrieve the list of foreign keys in an SQLite database
in Python?
a. Use the PRAGMA foreign_key_list() statement
b. Use the SHOW FOREIGN KEYS command
c. Use the foreign_keys() method
d. Use the PRAGMA foreign_key_list(table_name) statement
209. How do you retrieve the current date and time in SQLite using
Python?
a. Use the CURRENT_TIMESTAMP constant
b. Use the TIME command
c. Use the GET_DATE() function
d. Use the FETCH_DATE() function
216. How can you insert a document into a MongoDB collection using
Python?
a. Using the insert_one() method
b. Using the add() method
c. Using the create_document() method
d. Using the insert() method
222. How can you delete a document from a MongoDB collection using
Python?
a. Using the delete_one() method
b. Using the remove() method
c. Using the drop() method
d. Using the destroy() method
226. How can you drop an index from a MongoDB collection using
Python?
a. Using the drop_index() method
b. Using the remove_index() method
c. Using the delete_index() method
d. Using the drop() method
228. How can you perform a text search in a MongoDB collection using
Python?
a. Using the search_text() method
b. Using the find_text() method
c. Using the text() method
d. Using the search() method with $text operator
236. How can you use Python to create a TTL index on a field in a
MongoDB collection?
a. Using the create_ttl_index() method
b. Using the ttl() method
c. Using the create_index() method with the expireafterseconds
option
d. Using the set_ttl_index() method
242. How can you use Python to create a sparse index on a field in a
MongoDB collection?
a. Using the create_sparse_index() method
b. Using the sparse() method
c. Using the create_index() method with the sparse option
d. Using the set_sparse_index() method
244. How can you use Python to create a text index on multiple fields in
a MongoDB collection?
a. Using the create_text_index() method
b. Using the text_index() method
c. Using the create_index() method with the text option
d. Using the set_text_index() method
248. How can you use Python to create a hashed index on a field in a
MongoDB collection?
a. Using the create_hashed_index() method
b. Using the hashed_index() method
c. Using the create_index() method with the hashed option
d. Using the set_hashed_index() method
250. How can you use Python to create a 2dsphere index on a field in a
MongoDB collection?
a. Using the create_2dsphere_index() method
b. Using the 2dsphere_index() method
c. Using the create_index() ___________.method with the 2dsphere
option
d. Using the set_2dsphere_index() method
Conclusion
In conclusion, this chapter has explored the dynamic intersection of Python
and databases, offering a comprehensive understanding of the tools and
techniques necessary for effective database programming. From establishing
connections to executing queries, managing transactions, and handling data,
this chapter has equipped with the knowledge and practical skills needed to
navigate the world of databases seamlessly. As you continue your Python
journey, may the lessons learned here empower you to build sophisticated,
data-centric applications, ‘confidently and efficiently.
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No