MCQ
for
Python Users
Get ready for computer science
examinations
with 5000+ Python MCQ
Dr. Brijesh Bakariya
Dr. Krishna Kumar Mohbey
www.bpbonline.com
First Edition 2024
Copyright © BPB Publications, India
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.
LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY
The information contained in this book is true to correct and the best of author’s and publisher’s
knowledge. The author has made every effort to ensure the accuracy of these publications, but
publisher cannot be held responsible for any loss or damage arising from any information in this book.
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 is dedicated to our family members who have
supported us in all respects of life and career. Our journey
proved to be a boon by following their words and experiences.
About the Authors
Dr. Brijesh Bakariya is an Assistant Professor in the Department of
Computer Science and Engineering, I.K. Gujral Punjab Technical University
(IKGPTU) Campus Hoshiarpur, Punjab. He completed his Ph. D. at Maulana
Azad National Institute of Technology (NIT- Bhopal), Madhya Pradesh
(2016). He received an MCA Degree from Devi Ahilya Vishwavidyalaya,
Indore, Madhya Pradesh (2009). He has been teaching since 2009 and
guiding M.Tech/Ph.D. students. In the meantime, he has authored three books
and published more than 30 research papers in journals of international repute
in Data Mining, Machine Learning, Deep Learning, Image Processing,
Human Activity Recognition, and so on. He supervised three Ph.D. scholars,
and three are working with him. He has attended various short-term training
programs, refresher courses, workshops, seminars, and conferences in India.
Dr. Krishna Kumar Mohbey is an Assistant Professor of Computer Science
at the Central University of Rajasthan, India. He received his Bachelor’s
degree in Computer Applications from MCRPV Bhopal (2006), Master’s in
Computer Applications from Rajiv Gandhi Technological University Bhopal
(2009), and Ph.D. from the Department of Mathematics and Computer
Applications from National Institute of Technology Bhopal, India (2015). He
has been teaching since 2009 and guiding Ph.D. students. His areas of interest
are Machine learning, data mining, mobile web services, big data analysis,
POI Recommendations, and user behavior analysis. He has authored four
books on different subjects and published over 50 research articles in reputed
journals and conferences.
Acknowledgement
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 :
errata@bpbonline.com
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 :
business@bpbonline.com 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
business@bpbonline.com with a link to the material.
If you are interested in becoming an author
If there is a topic that you have expertise in, and you are interested in either writing or contributing
to a book, please visit www.bpbonline.com. We have worked with thousands of developers and
tech professionals, just like you, to help them share their insights with the global tech community.
You can make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Table of Contents
1. Fundamentals of Programming
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
2. Introduction to Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
3. Data type, Operators, and Expressions
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
4. Control Flow Statements
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
10. File Handling
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
11. Exception Handling
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
14. Object-oriented Programming
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
15. Graphical User Interfaces in Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
16. Machine Learning with Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
17. Clustering with Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
18. Applications of Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
19. Python Error Finding MCQ
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
20. Database Programming with Python
Introduction
Objectives
Multiple choice questions
Conclusion
Answers
CHAPTER 1
Fundamentals of Programming
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.
Multiple choice questions
1. Which translator program is responsible for converting an
assembly language program into an equivalent Machine Language
program?
a. Compiler
b. Linker
c. Assembler
d. Interpreter
2. An _______ is a symbol representing a particular operation that
can be performed on data.
a. Operand
b. Operator
c. Expression
d. None of the above
3. Which one of the following programming languages is machine-
independent?
a. High level language
b. Machine language
c. Assembly language
d. All the above
4. Which of the languages is said to be a high-level language?
a. C++ c. C
b. Java d. All the above
5. Which of the following translates the source program statements
into object codes?
a. Compiler
b. Debugger
c. Interpreter
d. Assembler
6. What is the primary purpose of a variable in programming?
a. To store and manipulate data
b. To control the flow of the program
c. To display output to the user
d. To comment on code
7. Which of the following data types is not typically used to store
numeric values?
a. int c. float
b. string d. double
8. What does the term algorithm mean when applied to computer
programming?
a. A programming language
b. A step-by-step procedure for solving a problem
c. A computer’s memory
d. A type of data structure
9. Which control structure is used to repeat a block of code until a
certain condition is met?
a. if statement
b. for loop
c. switch statement
d. function
10. What is the purpose of the if-else statement in programming?
a. To define a function
b. To execute a block of code only if a condition is true, and another
block, if it is false
c. To declare a variable
d. To create a loop
11. Which of the following is not a valid programming language?
a. Python c. HTML
b. JavaScript d. C++
12. What is the purpose of the while loop in programming?
a. To iterate over a sequence of values
b. To execute a block of code a specified number of times
c. To define a function
d. To check a condition and repeat the code if the condition is true
13. In programming, what do you understand by a function?
a. A piece of code that prints text to the screen
b. A container for storing data
c. A reusable block of code that performs a specific task
d. A type of loop
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
15. Which data structure uses the LIFO principle?
a. Queue
b. Stack
c. Linked list
d. Array
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
17. Which of the following is not a valid programming paradigm?
a. Object-Oriented Programming
b. Functional Programming
c. Procedural Programming
d. Circular Programming
18. In programming, what is a compiler?
a. A program that converts source code into machine code
b. A program used for debugging code
c. A program that generates random numbers
d. A program that displays output on the screen
19. Various programming languages use this operator to assign a
value to a variable:
a. +
b. =
c. :
d. *
20. What is the purpose of a comment in code?
a. To specify the input data
b. To improve the program’s performance
c. To explain or document the code for human readers
d. To declare a variable
21. Which programming construct allows a program to make
decisions and execute different codes based on conditions?
a. Loop
b. Function
c. Control structure
d. Conditional statement
22. What is the term for a named storage location in memory that
holds a value?
a. Function
b. Variable
c. Operator
d. Constant
23. Which of the following is a valid way to represent a single-line
comment in Python?
a. /* This is a comment */
b. // This is a comment
c. # This is a comment
d. <!-- This is a comment -->
24. What is the result of 5 % 2 in most programming languages?
a. 2.5
b. 2
c. 1.5
d. 1
25. In object-oriented programming, what is a class?
a. A function that performs a specific task
b. A template or blueprint for creating objects
c. A data structure used to store multiple values
d. An error in the code
26. What is the primary purpose of the break statement in a loop?
a. To terminate the program
b. To exit the loop and continue with the next iteration
c. To print a message to the console
d. To create a new loop
27. In programming, what is a parameter or argument in the context
of functions?
a. A variable declared inside a function
b. A variable used to store user input
c. A value passed into a function when it is called
d. A reserved keyword
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
29. Which of the following is NOT a valid data type in many
programming languages?
a. Boolean c. Character
b. Decimal d. Integer
30. What does the acronym HTTP stand for in web development?
a. Hyperlink Text Transfer Protocol
b. HyperText Transfer Protocol
c. High-Tech Transfer Protocol
d. HyperTransfer Text Protocol
31. In programming, what is the purpose of an array?
a. To store a single value
b. To store a collection of values of the same type
c. To perform mathematical calculations
d. To define a function
32. Which operator is used for logical NOT in many programming
languages?
a. && c. !
b. || d. ~
33. What does the term DRY stand for in programming?
a. ‘Don’t Repeat Yourself
b. Data Retrieval Yield
c. Debugging Rules for You
d. Dynamic Resource Yield
34. In object-oriented programming, what is inheritance?
a. A mechanism for defining classes
b. A way to create objects
c. A process where a class can inherit attributes and methods from
another class
d. A type of loop
35. Which of the following is NOT a commonly used programming
language?
a. Java
b. Ruby
c. Pascal
d. Monitor
36. What is data structure in programming?
a. A program’s user interface
b. A way to structure code
c. A way to organize and store data for efficient access and
modification
d. A type of algorithm
37. What is the purpose of the else if (or “elif”) statement in
programming?
a. To end the program
b. To specify the input data
c. To define a function
d. To provide an alternative condition to check if the initial
condition is false
38. What is typecasting in programming?
a. Casting a magic spell to fix errors in code
b. Converting a value from one data type to another
c. Declaring a variable with a specific type
d. A type of loop structure
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
40. What is the purpose of the “try...catch” or “try...except” block in
programming?
a. To execute code unconditionally
b. To handle and recover from exceptions or errors
c. To declare a function
d. To define a loop
41. In the context of object-oriented programming, what is
polymorphism?
a. A type of data structure
b. The ability of a function to accept different types of arguments
c. The ability of an object to take on many forms and respond
differently to the same method call
d. A type of loop control structure
42. What is debugging in programming?
a. Writing code without errors
b. A process of enhancing code performance
c. Identifying and fixing errors or defects in code
d. A method of creating data structures
43. In programming, what is a library or module?
a. A type of data structure
b. A collection of pre-written code that can be reused in other
programs
c. A variable used to store user input
d. A type of loop structure
44. What is the purpose of the for-each loop in programming?
a. To iterate over elements of an array or collection
b. To define a function
c. To execute code a specific number of times
d. To exit the program
45. What is the term for a collection of key-value pairs in
programming?
a. List c. Dictionary
b. Array d. Function
46. What does the acronym API stand for in programming?
a. Application Protocol Interface
b. Automated Program Integration
c. Application Programming Interface
d. Advanced Programming Interface
47. In programming, what is recursion?
a. A loop that repeats a block of code a specific number of times
b. A function that calls itself to solve a problem
c. A type of data structure
d. A way to comment code
48. What is source code in programming?
a. Code that is executed directly by the CPU
b. Code that is written by the programmer and can be edited
c. Code that is generated by a compiler
d. Code that is used for debugging
49. What is the purpose of the switch statement in programming?
a. To perform mathematical calculations
b. To define a loop
c. To execute a block of code based on the value of an expression
d. To create a custom data type
50. What is version control in software development?
a. A way to control access to the internet
b. A process of keeping track of changes to code over time
c. A type of programming language
d. A method of code optimization
51. In programming, what does the term scope refer to?
a. The size of the computer monitor
b. The range of visibility and accessibility of variables
c. The speed of program execution
d. A data structures
52. Which of the following is NOT a commonly used programming
paradigm?
a. Object-Oriented Programming
b. Functional Programming
c. Linear Programming
d. Procedural Programming
53. What is a pointer in programming?
a. A device used for input
b. A variable that stores a memory address
c. A type of loop
d. A reserved keyword
54. What is the purpose of the continue statement in a loop?
a. To terminate the loop
b. To exit the program
c. To skip the current iteration and continue with the next iteration
d. To print a message to the console
55. Which of the following is an example of a high-level programming
language?
a. Assembly language
b. C
c. Machine code
d. Python
56. What is garbage collection in programming?
a. A process of disposing of unused computer hardware
b. A method of sorting data
c. A technique for automatically reclaiming memory occupied by
objects that are no longer in use
d. A way to optimize network communication
57. In programming, what is concurrency?
a. A type of loop
b. The ability of a program to execute multiple tasks simultaneously
c. A way to declare variables
d. A form of data encryption
58. What is a bit in computing?
a. A small program
b. A binary digit, either 0 or 1
c. A unit of time measurement
d. A type of variable
59. Which of the following is NOT a common data structure in
programming?
a. Stack c. Graph
b. Queue d. String
60. What is debugging by print in programming?
a. A method of fixing errors in code by erasing code
b. A way to debug code by adding print statements to display
variable values
c. A type of loop structure
d. A form of code optimization
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
62. What is a byte in computing?
a. A binary digit
b. A unit of memory that typically stores one character
c. A type of loop control structure
d. A data type used for floating-point numbers
63. What is pair programming in software development?
a. Writing code in pairs of two
b. Programming using only two programming languages
c. A form of code optimization
d. A method of solving math problems
64. In programming, what is abstraction?
a. The process of making code more complex
b. A method of code optimization
c. The process of simplifying complex systems by breaking them
into smaller, manageable parts
d. A type of loop structure
65. What is asynchronous programming?
a. A type of programming that runs on asynchronous hardware
b. A way to write code that executes sequentially
c. A programming paradigm that emphasizes timing precision
d. A style of programming that allows tasks to run independently
and be completed when ready
66. What is code refactoring in programming?
a. A process of rewriting code from scratch
b. A method for introducing new bugs into existing code
c. The practice of improving the structure and readability of code
without changing its external behavior
d. A type of software testing
67. What is the purpose of the NaN value in programming?
a. To represent a null value
b. To indicate a syntax error
c. To represent a non-numeric or undefined value
d. To calculate mathematical constants
68. Which of the following is an example of a shell in the context of
programming?
a. A type of data structure
b. A user interface for a computer’s operating system
c. A form of encryption
d. A way to store variables
69. What is agile development in software engineering?
a. A development approach that emphasizes heavy documentation
b. A methodology that focuses on rigid project planning and strict
adherence to schedules
c. An iterative and flexible approach to software development that
values customer collaboration and responsiveness to change
d. A type of software architecture
70. In programming, what is bitwise AND used for?
a. Performing logical negation
b. Combining two numbers by adding them
c. Combining two binary numbers bit by bit, producing a result with
1s only where both inputs have 1s
d. Performing division
71. What is “aggregation” in object-oriented programming?
a. A process of combining data from different sources
b. A way to declare variables
c. A type of loop structure
d. A relationship where one class is composed of multiple instances
of another class
72. What is object serialization in programming?
a. A method of object destruction
b. The process of converting an object into a format that can be
stored or transmitted
c. A way to optimize code
d. A type of memory management
73. What is Big O notation used for in computer science?
a. A way to represent large numbers
b. A method of code refactoring
c. A mathematical notation used to describe the performance or
complexity of an algorithm
d. A type of loop structure
74. What is pairwise swapping in sorting algorithms?
a. A method of code optimization
b. A process of data encryption
c. A technique used to sort elements in pairs
d. A way to declare variables
75. What is shallow copy and deep copy in programming?
a. Two different programming languages
b. Two ways to create comments in code
c. Two methods of object serialization
d. Two ways to duplicate objects where a shallow copy only
duplicates the top-level object, while a deep copy duplicates all
nested objects
76. What is a lambda function in programming?
a. A function that is written in a foreign language
b. A type of loop structure
c. An anonymous function that can be used as an argument to other
functions
d. A method for data encryption
77. What is dependency injection in software design?
a. A process of adding external dependencies to a program
b. A way to optimize code
c. A design pattern where dependencies are provided to a class
rather than being created or managed within the class
d. A method of object serialization
78. What is dynamic typing in programming languages?
a. A method of code refactoring
b. A way to optimize code
c. A feature where variables can change their data type during
runtime
d. A type of loop control structure
79. Which of the following is not a high-level programming language?
a. Python
b. Java
c. Assembly language
d. C#
80. What is the primary advantage of using high-level programming
languages over low-level languages?
a. High-level languages are faster in execution.
b. High-level languages provide better control over hardware.
c. High-level languages are more platform-independent and easier
to read and write.
d. High-level languages use less memory.
81. Which of the following high-level programming languages is
known for its simplicity and readability?
a. C++ c. Python
b. Perl d. Ruby
82. In high-level programming languages, what is the purpose of a
compiler?
a. To convert the source code into machine code
b. To execute the program
c. To generate random numbers
d. To create user interfaces
83. Which of the following is an example of a high-level programming
language used for web development?
a. HTML c. JavaScript
b. CSS d. SQL
84. Which high-level programming language is often used for
scientific and numerical computing due to its extensive libraries?
a. Java
b. Ruby
c. MATLAB
d. Swift
85. What is an interpreted language in the context of high-level
programming languages?
a. A language that compiles code to machine language before
execution
b. A language that directly executes source code line by line without
a separate compilation step
c. A language that is used only for numerical calculations
d. A language that is no longer in use
86. Which of the following high-level programming languages is often
used for game development?
a. Python
b. C#
c. Perl
d. Ruby
87. Which of the following is a high-level programming language used
for data analysis and manipulation?
a. Java
b. C++
c. R
d. Swift
88. Which high-level programming language is known for its use in
web development, especially for creating dynamic web pages?
a. Java
b. PHP
c. C#
d. Swift
89. What does object-oriented programming refer to in high-level
programming languages?
a. A programming paradigm that focuses on optimizing code for
performance
b. A programming paradigm that emphasizes organizing code
around objects, which encapsulate data and behavior
c. A programming language with a simple and minimalistic syntax
d. A type of database management system
90. Which of the following is an example of a high-level programming
language used for Artificial Intelligence and Machine Learning?
a. Java
b. Python
c. C++
d. Perl
91. What is a high-level scripting language in high-level programming
languages?
a. A language that requires explicit declaration of data types for
variables
b. A language that is used exclusively for scripting web pages
c. A language that is primarily used for game development
d. A language that provides built-in high-level functions and
features for ease of use
92. Which of the following high-level programming languages is
known for its use in mobile app development, particularly for iOS
devices?
a. Java c. Swift
b. Python d. Ruby
93. What is garbage collection in high-level programming languages?
a. A process of disposing of unused computer hardware
b. A technique for optimizing database queries
c. A mechanism for automatically reclaiming memory occupied by
objects that are no longer in use
d. A method of object serialization
94. In high-level programming languages, what is a variable?
a. A reserved keyword
b. A container for storing and manipulating data
c. A data type used for floating-point numbers
d. A method of code refactoring
95. What is functional programming in high-level programming
languages?
a. A programming paradigm that focuses on code organization
around objects
b. A programming paradigm that emphasizes using functions as the
primary building blocks of code
c. A type of database management system
d. A way to create graphical user interfaces
96. In high-level programming languages, what is exception handling?
a. A process of creating custom data types
b. A method of data encryption
c. A mechanism for dealing with unexpected errors or exceptional
conditions during program execution
d. A way to declare variables
97. Which of the following is not a commonly used high-level
programming language?
a. JavaScript
b. Ruby
c. Assembly Language
d. Swift
98. Which of the following is a major challenge in machine
translation?
a. Perfect translation accuracy
b. Consistency in terminology
c. Handling of idiomatic expressions
d. Limited availability of translation APIs
99. What does the term source language refer to in translation?
a. The language of the translator
b. The language from which the text is being translated
c. The target language
d. The language of the original author
100. Which of the following is an example of a Computer-Assisted
Translation (CAT) tool commonly used by professional
translators?
a. Google Translate
b. SDL Trados
c. Duolingo
d. Microsoft Word
101. What is a “CAT tool plugin” used for?
a. To play audio translations
b. To extend the functionality of Computer-Assisted Translation
(CAT) tools
c. To convert text to speech
d. To translate handwritten documents
102. Which technology is used for speech-to-text transcription in
translation?
a. Optical Character Recognition (OCR)
b. Automatic Speech Recognition (ASR)
c. Translation memory
d. Machine translation
103. What is phrase-based translation in machine translation?
a. A translation method that relies on short phrases rather than full
sentences for better accuracy
b. A translation technique that uses idiomatic expressions for
translation
c. A form of human-assisted translation
d. A translation approach that exclusively uses neural networks
104. What is the primary purpose of an assembler in computer
programming?
a. To translate high-level code into machine code
b. To optimize code for performance
c. To convert assembly language code into machine code
d. To execute programs
105. Which of the following is a characteristic of assembly language?
a. It is a high-level programming language
b. It is easy to read and write for humans
c. It is machine-dependent and closely tied to a specific computer
architecture
d. It uses natural language for programming
106. What is the main role of a compiler in the software development
process?
a. To execute code directly
b. To convert high-level programming code into machine code or an
intermediate representation
c. To interpret code line by line
d. To optimize code for better performance
107. In the context of compilers, what does optimization refer to?
a. The process of making code more readable for humans
b. The process of improving code execution speed and efficiency
c. The process of translating code into multiple languages
d. The process of debugging code
108. Which of the following statements is true regarding interpreters?
a. Interpreters convert high-level code into machine code before
execution.
b. Interpreters generate standalone executable files.
c. Interpreters execute code line by line without creating a separate
compiled version.
d. Interpreters are primarily used for optimizing code.
109. What is the advantage of using an interpreter over a compiler?
a. Interpreters produce faster-executing code.
b. Interpreters provide stronger type checking.
c. Interpreters allow for easier debugging and faster development.
d. Interpreters create smaller executable files.
110. Which phase of the compilation process is responsible for checking
the source code for syntax errors?
a. Parsing
b. Optimization
c. Code generation
d. Lexical analysis
111. What is the purpose of the linker in the compilation process?
a. To convert high-level code into assembly language
b. To combine object files into a single executable program
c. To check for syntax errors in the source code
d. To optimize the code for execution
112. Which programming languages are typically compiled into
machine code before execution?
a. Python c. C++
b. Java d. JavaScript
113. What just-in-time (JIT) compilation in programming languages?
a. A compilation process that occurs before the code is executed
b. A technique used in assembly language programming
c. A method of code optimization
d. A compilation process that happens at runtime, converting
bytecode into machine code
114. Which of the following is an example of a compiled programming
language?
a. Python c. C#
b. Ruby d. JavaScript
115. What is the primary advantage of using a compiled language over
an interpreted language?
a. Compiled languages are more portable
b. Compiled languages are easier to debug
c. Compiled languages typically offer better performance
d. Compiled languages are more human-readable
116. Which programming language is commonly used for writing
scripts that are interpreted rather than compiled?
a. C++ c. Perl
b. Java d. Fortran
117. What is the main role of the pre-processor in C and C++
programming?
a. To optimize code for execution
b. To translate high-level code into assembly language
c. To remove comments and whitespace from the source code
d. To handle macro substitutions and include header files
118. In the context of interpreters, what is the purpose of the “runtime
environment”?
a. To convert source code into machine code
b. To provide a development environment for programmers
c. To execute code and manage its execution context
d. To optimize code for better performance
119. What is a virtual machine in the context of interpreted languages
like Java?
a. A physical computer used for code execution
b. A software-based emulation of a computer that executes bytecode
c. A debugging tool for programmers
d. A hardware component that speeds up code execution
120. Which of the following languages is commonly associated with the
use of a virtual machine?
a. C c. Python
b. Java d. PHP
121. What is bytecode in the context of Java programming?
a. Machine code directly executable by the computer’s CPU
b. Intermediate code that is executed by the Java Virtual Machine
(JVM)
c. Source code written in the Java programming language
d. A low-level programming language
122. Which of the following is an example of an interpreted
programming language?
a. C++ c. Fortran
b. Python d. Swift
123. What is an algorithm?
a. A type of data structure
b. A step-by-step procedure for solving a problem or performing a
task
c. A programming language
d. A hardware component
124. Which of the following is NOT a characteristic of a good
algorithm?
a. Efficiency c. Ambiguity
b. Simplicity d. Correctness
125. What is the time complexity of an algorithm?
a. The amount of memory it uses
b. The number of steps it takes to solve a problem in terms of the
input size
c. The number of variables it uses
d. The quality of the code it produces
126. What is the space complexity of an algorithm?
a. The amount of physical space required to store the algorithm
b. The amount of memory it uses
c. The number of steps it takes to solve a problem
d. The efficiency of the algorithm
127. Which of the following sorting algorithms has a worst-case time
complexity of O(n^2)?
a. Merge sort
b. Quick sort
c. Bubble sort
d. Radix sort
128. What is recursion in the context of algorithms?
a. A type of data structure
b. A loop construct
c. A problem-solving approach that involves solving smaller
instances of the same problem
d. An efficient sorting algorithm
129. Which algorithmic paradigm involves dividing a problem into
smaller subproblems and solving each subproblem independently
before combining the results?
a. Divide and conquer
b. Greedy algorithms
c. Dynamic programming
d. Backtracking
130. What is the primary advantage of using dynamic programming in
algorithm design?
a. It is easy to implement.
b. It is always the most efficient algorithmic approach.
c. It can solve problems with overlapping subproblems more
efficiently by storing and reusing intermediate results.
d. It requires minimal memory usage.
131. Which of the following is NOT a common data structure used in
algorithm design?
a. Arrays
b. Stacks
c. Algorithms
d. Linked lists
132. What is Big O notation used for in algorithm analysis?
a. To describe the efficiency of algorithms in terms of their running
time
b. To represent very large numbers
c. To define recursive functions
d. To specify the order of function arguments
133. In algorithm analysis, what does O(n) represent?
a. An algorithm with constant time complexity
b. An algorithm with logarithmic time complexity
c. An algorithm with linear time complexity
d. An algorithm with exponential time complexity
134. What is space-time trade-off in algorithm design?
a. The process of exchanging time complexity for space complexity
b. The process of optimizing both time and space complexity
simultaneously
c. The process of minimizing the use of both time and space
d. The process of optimizing algorithms for parallel execution
135. Which search algorithm is commonly used for searching sorted
arrays?
a. Linear search
b. Binary search
c. Depth-first search
d. Breadth-first search
136. What is the primary purpose of the greedy approach in algorithm
design?
a. To solve problems by considering all possible solutions
b. To solve problems by making locally optimal choices at each step
c. To solve problems by backtracking through all possible
combinations
d. To solve problems by using dynamic programming
137. Which algorithmic paradigm involves trying all possible solutions
and selecting the best one?
a. Divide and conquer
b. Greedy algorithms
c. Dynamic programming
d. Backtracking
138. What is a heuristic in the context of algorithms?
a. A data structure
b. A search algorithm
c. A problem-solving approach that uses rules of thumb to make
decisions
d. A sorting algorithm
139. Which of the following is NOT a common sorting algorithm?
a. Quick sort c. Hash sort
b. Bubble sort d. Merge sort
140. What is the primary objective of optimization algorithms?
a. To find the worst-case scenario
b. To find the most complex solution
c. To find the optimal solution that maximizes or minimizes a
specific objective
d. To find the average-case scenario
141. What does NP-complete mean in the context of computational
complexity theory?
a. Problems that are easy to solve in polynomial time
b. Problems that are intractable and cannot be solved in polynomial
time
c. Problems that have only one possible solution
d. Problems that have a single optimal solution
142. Which of the following is an example of a problem that belongs to
the P complexity class?
a. The traveling salesman problem
b. The knapsack problem
c. Sorting a list of integers
d. The Sudoku puzzles
143. What is a flowchart?
a. A type of computer hardware
b. A graphical representation of an algorithm or process
c. A programming language
d. A flow of data between different devices
144. What is the standard symbol used in a flowchart to represent a
process or operation?
a. Rectangle c. Oval
b. Diamond d. Parallelogram
145. In a flowchart, what shape is typically used to represent a decision
or conditional statement?
a. Rectangle c. Oval
b. Diamond d. Parallelogram
146. Which of the following flowchart symbols represents the start or
beginning of a process?
a. Rectangle
b. Diamond
c. Oval
d. Parallelogram
147. What is the purpose of using arrows in a flowchart?
a. To indicate the direction of data flow
b. To connect shapes and make the flowchart look attractive
c. To represent mathematical operations
d. To indicate decision points
148. In a flowchart, what does a rectangle with rounded corners
typically represent?
a. A process or operation
b. A decision point
c. The start or end of a process
d. Data input or output
149. Which flowchart symbol represents the end of a process or
algorithm?
a. Rectangle
b. Diamond
c. Oval
d. Parallelogram
150. In a flowchart, what does a parallelogram symbolize?
a. A process or operation
b. A decision or conditional statement
c. Data input or output
d. A loop
151. What is the purpose of using connectors or off-page reference
symbols in a flowchart?
a. To indicate decision points
b. To connect multiple pages or sections of a flowchart
c. To represent mathematical operations
d. To indicate the start of a process
152. Which flowchart symbol is used to represent a subroutine or
module in a larger flowchart?
a. Rectangle
b. Diamond
c. Oval
d. Rectangle with double lines
153. What is the primary purpose of using flowcharts in problem-
solving and process documentation?
a. To write code for software development
b. To visualize and analyze complex processes or algorithms
c. To create artistic designs
d. To perform mathematical calculations
154. Which of the following statements is true regarding the direction
of flow in a flowchart?
a. Flowcharts must always flow from right to left.
b. Flowcharts can flow in any direction, depending on the
preference of the designer.
c. Flowcharts must always flow from left to right.
d. Flowcharts must always flow from top to bottom.
155. In a flowchart, what does a terminator symbol (for example, a
circle) represent?
a. A decision point
b. The start of a process
c. The end of a process
d. Data input or output
156. What is the purpose of using flowchart annotations or comments?
a. To label the shapes in a flowchart
b. To provide additional information or explanations about the
flowchart
c. To connect shapes together
d. To indicate the start of a process
157. Which flowchart symbols represent a data storage element, such
as a database or file?
a. Rectangle c. Oval
b. Diamond d. Parallelogram
158. In a flowchart, what does a rectangle with double lines typically
represent?
a. A decision point
b. A data input or output
c. A subroutine or module
d. The start of a process
159. What is the purpose of using a flowchart legend?
a. To indicate the start of a process
b. To provide a summary of the flowchart’s content
c. To specify the direction of the flow
d. To add aesthetic elements to the flowchart
160. Which of the following is NOT a standard shape used in
flowcharts?
a. Triangle c. Diamond
b. Rectangle d. Oval
161. What type of flowchart is commonly used to represent the steps
involved in solving a specific problem or task?
a. System flowchart
b. Process flowchart
c. Program flowchart
d. Decision flowchart
162. In a flowchart, what does a line with an arrowhead indicate?
a. The end of the flowchart
b. The start of a process
c. The direction of flow
d. A decision point
163. What does SDLC stand for in the context of software
development?
a. System Design and Life Cycle
b. Software Development Life Cycle
c. Systems Development and Life Cycle
d. Systems Design and Lifecycle Control
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
167. Which phase of the SDLC involves coding and programming?
a. Requirements phase
b. Design phase
c. Development phase
d. Testing phase
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
169. What is the purpose of the implementation phase in the SDLC?
a. To gather and analyze user requirements
b. To design the system architecture
c. To deploy the software for use by end-users
d. To create detailed design specifications
170. Which phase of the SDLC involves preparing user documentation
and training materials?
a. Requirements phase
b. Design phase
c. Development phase
d. Implementation phase
171. In the SDLC, what is the role of the “maintenance” phase?
a. To gather and analyze user requirements
b. To design the system architecture
c. To fix defects, enhance functionality, and adapt the software to
changing needs
d. To write code and develop the software
172. Which of the following is a benefit of using the SDLC in software
development?
a. It accelerates the development process by skipping the design
phase.
b. It reduces the need for user involvement.
c. It provides a structured and organized approach to development.
d. It eliminates the need for testing.
173. What is the purpose of a feasibility study in the SDLC?
a. To assess whether the project is technically feasible
b. To determine if the project is financially viable
c. To evaluate the skills of the development team
d. To create user documentation
174. Which SDLC model involves completing each phase in a linear
sequence with no overlap?
a. Waterfall model c. Spiral model
b. Agile model d. RAD model
175. What is a characteristic of the Agile SDLC model?
a. It is a sequential and linear approach to software development.
b. It prioritizes comprehensive documentation over working
software.
c. It emphasizes collaboration, flexibility, and incremental
development.
d. It does not involve end-user feedback.
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
179. Which SDLC model is characterized by its focus on rapid
development and frequent user feedback?
a. Waterfall model
b. Agile model
c. Spiral model
d. V-Model
180. In the SDLC, what is the primary goal of the deployment phase?
a. To gather and analyze user requirements
b. To create design specifications
c. To deploy the software for use by end-users
d. To perform code development
181. What is the primary role of a project manager in the SDLC?
a. To write code and develop the software
b. To gather user requirements
c. To oversee and coordinate the entire software development
process
d. To perform software testing
182. Which SDLC model is also known as the Verification and
Validation model?
a. Waterfall model
b. Agile model
c. Spiral model
d. V-Model
183. What is pseudocode?
a. A type of programming language
b. A formal and precise programming language
c. A high-level programming language
d. A way to outline a program’s logic using plain language and
simple constructs
184. What is the primary purpose of pseudocode?
a. To serve as the final code for a program
b. To provide a step-by-step algorithmic description of a program’s
logic
c. To replace the need for actual programming languages
d. To create visual designs for user interfaces
185. Which of the following statements is true about pseudocode?
a. Pseudocode is a formal programming language with strict syntax
rules.
b. A computer can execute pseudocode.
c. Pseudocode is primarily used for final program implementation.
d. Pseudocode uses natural language and simple syntax to describe
algorithms.
186. What does pseudo in pseudocode signify?
a. It means false or fake.
b. It stands for a specific programming language.
c. It indicates precision and formality.
d. It denotes simplicity and readability.
187. Which of the following is a common way to represent assignment
statements in pseudocode?
a. Using the assignment operator “:=”
b. Using the equals sign “=”
c. Using the “let” keyword
d. Using square brackets “[]”
188. In pseudocode, what is the purpose of using indentation?
a. To increase the complexity of the code
b. To create visual patterns in the code
c. To improve code readability and indicate block structures
d. To generate error messages
189. Which pseudocode constructs are used to repeat a set of
statements until a certain condition is met?
a. If-Else statement
b. Switch statement
c. While loop
d. Function definition
190. What is the pseudocode equivalent of an if-else statement in
programming?
a. Conditional expression
b. Decision tree
c. Case statement
d. If-Else statement
191. Which pseudocode construct is used to define and encapsulate a
reusable block of code?
a. Function
b. Loop
c. Variable
d. Decision structure
192. In pseudocode, how do you typically represent input and output
operations?
a. Using the “PRINT” and “READ” keywords
b. Using mathematical symbols
c. Using square brackets “[]”
d. Using the “FOR” and “WHILE” keywords
193. What is a variable in programming?
a. A fixed value
b. A reserved word in a programming language
c. A container for storing data that can change during program
execution
d. A mathematical operator
194. In most programming languages, which keyword is used to declare
a variable?
a. “Declare”
b. “Variable”
c. “Let”
d. The actual variable name
195. What is the purpose of declaring a variable before using it in a
program?
a. To reserve memory space for the variable
b. To make the variable constant and unchangeable
c. To hide the variable from the rest of the program
d. To indicate that the variable is not needed
196. Which of the following is a valid variable name in most
programming languages?
a. 123variable
b. my_variable_1
c. @variable
d. variable name
197. What is a keyword in programming?
a. A unique identifier for a variable
b. A reserved word with a special meaning in the programming
language
c. A variable that holds only numeric values
d. A type of data structure
198. In programming, what happens if you try to use a keyword as a
variable name?
a. The program will generate an error.
b. The variable will be automatically declared.
c. The variable will be assigned a default value.
d. The keyword will become a variable.
199. Which of the following is NOT a common keyword in
programming languages?
a. if c. variable
b. else d. while
200. What is the purpose of keywords like “if” and “else” in
programming?
a. To define variable names
b. To indicate the start of a program
c. To control the flow of program execution based on conditions
d. To perform mathematical calculations
201. In many programming languages, what keyword is used to start a
loop?
a. start
b. loop
c. for
d. then
202. What is the significance of case sensitivity when using variable
names and keywords in programming languages?
a. It has no impact on program execution.
b. Variable names and keywords must always be in lowercase.
c. Variable names and keywords must always be in uppercase.
d. Variable names and keywords are treated as distinct based on
case.
203. In programming, what does “I/O” stand for?
a. Input/Output
b. Internal/Output
c. Input/Operations
d. Information/Output
204. Which of the following is an example of an input device used in
I/O operations?
a. Monitor
b. Printer
c. Keyboard
d. Speaker
205. What is the primary purpose of input instructions in
programming?
a. To display information to the user
b. To perform calculations
c. To read data from external sources into the program
d. To control program flow
206. Which of the following is not a common method for input in
programming?
a. Reading from a file
b. Keyboard input
c. Mouse input
d. Scanning a barcode
207. In programming, what does “stdout” typically refer to?
a. Standard output stream for displaying text to the screen
b. Standard input stream for reading data from the keyboard
c. A specialized input device
d. A type of keyboard layout
208. Which of the following is not a common method for output in
programming?
a. Writing to a file
b. Displaying text on the screen
c. Sending data over a network
d. Reading data from the keyboard
209. What is the purpose of formatting output in programming?
a. To make the code more readable
b. To ensure that all data is displayed on the screen
c. To control the appearance and layout of the output
d. To hide the output from the user
210. In many programming languages, what is the function used to
display output to the screen?
a. print() c. read()
b. input() d. write()
211. What is newline character in programming?
a. A character that represents the end of a file
b. A character that moves the cursor to the beginning of the line
c. A character that indicates the end of a line and starts a new line
d. A character that cannot be displayed on the screen
212. Which of the following is an example of an output device used in
I/O operations?
a. Mouse
b. Keyboard
c. Monitor
d. Hard drive
213. In programming, what does the term arithmetic instruction refer
to?
a. Instructions for controlling program flow
b. Instructions for performing mathematical operations
c. Instructions for input and output
d. Instructions for declaring variables
214. Which of the following is NOT a basic arithmetic operation in
programming?
a. Addition
b. Multiplication
c. Concatenation
d. Subtraction
215. In most programming languages, what symbol is used for
addition?
a. *
b. /
c. +
d. -
216. Which operator is used for exponentiation in programming?
a. ^
b. %
c. *
d. /
217. What is the operator precedence rule that specifies that
multiplication and division should be performed before addition
and subtraction?
a. Left-to-right associativity
b. Right-to-left associativity
c. BODMAS
d. Parentheses rule
218. In programming, what is the result of the expression 10 / 2?
a. 5.0
b. 5
c. 0.5
d. 10
219. Which operator is used for finding the remainder of a division
operation?
a. %
b. /
c. *
d. ^
220. What is the result of the expression 17 % 4?
a. 21
b. 4.25
c. 1
d. 0
221. What is the operator used for incrementing a variable by 1 in
programming?
a. ++
b. --
c. +=
d. =
222. Which of the following is NOT a valid mathematical operation in
programming?
a. Division by zero
b. Square root of a negative number
c. Multiplication of two integers
d. Addition of two floating-point numbers
223. What is the result of the expression 8 - 12?
a. -4
b. 4
c. 96
d. -96
224. Which operator is used for decrementing a variable by 1 in
programming?
a. ++
b. --
c. +=
d. =
225. Which operator is used for performing a logical AND operation in
programming?
a. &
b. |
c. ^
d. &&
226. Which operator is used for performing a logical OR operation in
programming?
a. &
b. |
c. ^
d. ||
227. What is the result of the expression (4 + 5) * 3?
a. 27
b. 14
c. 27.0
d. 0
228. Which of the following is NOT a common data type used in
arithmetic operations in programming?
a. Integer
b. Float
c. String
d. Double
229. Which of the following is not an Object-Oriented Language
(OOL)?
a. Python
b. JAVA
c. C++
d. C
230. Which of the following is a type of sorting algorithm?
a. Binary search
b. Quick sort
c. Depth-first search
d. Breadth-first search
231. Which keyword is used for defining a function in most
programming languages?
a. def
b. fun
c. sub
d. function
232. Which of the following is not a relational operator in most
programming languages?
a. =
b. ==
c. !=
d. ++
233. Which of the following is a type of web development framework?
a. Django
b. React
c. Angular
d. All of the above
234. Which of the following is not a data structure?
a. Stack
b. Queue
c. Function
d. Linked list
235. Which of the following is a commonly used Integrated
Development Environment (IDE) for Python?
a. Visual Studio Code
b. PyCharm
c. Eclipse
d. Sublime Text
236. Which of the following is a commonly used Object-Oriented
Programming Language (OOPL)?
a. C
b. Python
c. Perl
d. Shell
237. Which of the following is a commonly used web development
framework for PHP?
a. Laravel
b. Flask
c. Ruby on Rails
d. Express.js
238. Which of the following is a commonly used web development
framework for JavaScript?
a. Django
b. Flask
c. Ruby on Rails
d. React
239. Which of the following is a commonly used web development
framework for Python?
a. Django
b. Flask
c. Ruby on Rails
d. Express.js
240. A diagram which shows the relationship between classes is termed
as:
a. Class diagram
b. sequential diagram
c. use case diagram
d. communication diagram
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
246. Scala is the short form of:
a. Scalable language
b. Sequential language
c. Script language
d. Scalar language
247. Android operating system was acquired by Google in:
a. 2002
b. 2004
c. 2005
d. 2007
248. Today’s fastest-growing mobile phone operating system is:
a. Apple’s IOS
b. Google’s Android
c. Mac OS X
d. Blackberry OS
249. A mobile operating system is _____________.
a. Linux
b. Windows 10
c. Mac OS X
d. Blackberry OS
250. Python is said to be an easily _____________.
a. Readable language
b. Writable language
c. Bug-able language
d. Script-able language
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 c 51 b 101 b 151 b 201 c
2 b 52 c 102 b 152 d 202 d
3 a 53 b 103 a 153 b 203 a
4 d 54 c 104 c 154 b 204 c
5 a 55 d 105 c 155 c 205 c
6 a 56 c 106 b 156 b 206 c
7 b 57 b 107 b 157 c 207 a
8 b 58 b 108 c 158 c 208 d
9 b 59 d 109 c 159 b 209 c
10 b 60 b 110 a 160 a 210 a
11 c 61 a 111 b 161 b 211 c
12 d 62 b 112 c 162 c 212 c
13 c 63 a 113 d 163 b 213 b
14 d 64 c 114 c 164 c 214 c
15 b 65 d 115 c 165 d 215 c
16 b 66 c 116 c 166 c 216 a
17 d 67 c 117 d 167 c 217 c
18 a 68 b 118 c 168 b 218 a
19 b 69 c 119 b 169 c 219 a
20 c 70 c 120 b 170 d 220 c
21 d 71 d 121 b 171 c 221 a
22 b 72 b 122 b 172 c 222 b
23 c 73 c 123 b 173 b 223 a
24 d 74 c 124 c 174 a 224 b
25 b 75 d 125 b 175 c 225 d
26 b 76 c 126 b 176 c 226 b
27 c 77 c 127 c 177 b 227 a
28 a 78 c 128 c 178 c 228 c
29 b 79 c 129 a 179 b 229 d
30 b 80 c 130 c 180 c 230 b
31 b 81 c 131 c 181 c 231 a
32 c 82 a 132 a 182 d 232 d
33 a 83 c 133 c 183 d 233 d
34 c 84 c 134 a 184 b 234 c
35 d 85 b 135 b 185 d 235 b
36 c 86 b 136 b 186 a 236 b
37 d 87 c 137 d 187 a 237 a
38 b 88 b 138 c 188 c 238 d
39 a 89 b 139 c 189 c 239 a
40 b 90 b 140 c 190 d 240 a
41 c 91 d 141 b 191 a 241 a
42 c 92 c 142 c 192 a 242 b
43 b 93 c 143 b 193 c 243 d
44 a 94 b 144 a 194 c 244 a
45 c 95 b 145 b 195 a 245 b
46 c 96 c 146 c 196 b 246 a
47 b 97 c 147 a 197 b 247 c
48 b 98 c 148 a 198 a 248 b
49 c 99 b 149 c 199 c 249 d
50 b 100 b 150 c 200 c 250 a
CHAPTER 2
Introduction to Python
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.
Multiple choice questions
1. Who developed the Python programming language?
a. Guido van Rossum
b. James Gosling
c. Bjarne Stroustrup
d. Dennis Ritchie
2. What type of programming language is Python?
a. Interpreted
b. Compiled
c. Both interpreted and compiled
d. None of the above
3. What is the correct extension for a Python file?
a. .py
b. .pyc
c. .pyo
d. All of the above
4. Which of the following is a Python keyword?
a. print
b. def
c. if
d. All of the above
5. How is a code block indicated in Python?
a. Using curly braces ({})
b. Using indentation
c. Both (a) and (b)
d. None of the above
6. What is the output of the following Python code:
print("Hello, world!")
a. “Hello, world!” c. An error
b. None d. All of the above
7. What is the difference between the == and is operators in Python?
a. The == operator compares the values of two objects, while the is
operator compares the identity of two objects.
b. The == operator compares the values of two objects, while the is
operator compares the type of two objects.
c. The == operator compares the identity of two objects, while the is
operator compares the values of two objects.
d. The == operator compares the type of two objects, while the is
operator compares the identity of two objects.
8. What is a variable in Python?
a. A reserved memory location to store values. A named storage
location for data.
b. A piece of code that is executed repeatedly.
c. A function that is used to perform a specific task.
d. All of the above
9. What is the difference between a list and a tuple in Python?
a. A list is mutable, while a tuple is immutable.
b. A list is ordered, while a tuple is unordered.
c. A list can contain any type of data, while a tuple can only contain
primitive data types.
d. All of the above
10. What is the output of the following Python code?
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
a. [2, 3] c. An error
b. [2, 3, 4] d. None of the above
11. What is a function in Python?
a. A block of code that can be reused
b. A variable that can store a function
c. A statement that is executed when a certain condition is met
d. All of the above
12. What is the difference between a parameter and an argument in
Python?
a. A parameter is the variable that is defined in the function
definition, while an argument is the value that is passed to the
function when it is called.
b. A parameter is the value that is passed to the function when it is
called, while an argument is the variable that is defined in the
function definition.
c. A parameter is a named variable, while an argument is an
unnamed value.
d. A parameter is a primitive data type, while an argument is a
complex data type.
13. What is the output of the following Python code:
def my_function(x):
return x * 2
print(my_function(3))
The output will be:
a. 3 c. 9
b. 6 d. None of the above
14. Which of the following is a valid Python identifier?
a. my-variable
b. 1st_variable
c. _variable1
d. All of the above
15. What is the output of the following Python code:
my_string = "Hello, world!"
print(my_string[0:5])
a. “Hello”
b. “world!”
c. An error
d. None of the above
16. What is the difference between a break statement and a continue
statement in Python?
a. A break statement terminates the current loop, while a continue
statement skips the rest of the current iteration of the loop and
goes to the next iteration.
b. A break statement skips the rest of the current iteration of the
loop and goes to the next iteration, while a continue statement
terminates the current loop.
c. A break statement terminates the current function, while a
continue statement skips the rest of the current function and goes
to the next function.
d. A break statement skips the rest of the current function and goes
to the next function, while a continue statement terminates the
current function.
17. What is the output of the following Python code:
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i % 2 == 0:
print(i)
a. 1 c. 4
b. 2 d. All of the above
18. What is a dictionary in Python?
a. A collection of key-value pairs
b. An ordered collection of unique elements
c. A mutable collection of elements
d. All of the above
19. What is the difference between a list and a set in Python?
a. A list is ordered and mutable, while a set is unordered and
immutable.
b. A list is unordered and mutable, while a set is ordered and
immutable.
c. A list is mutable and can contain any type of data, while a set is
immutable and can only contain unique elements.
d. A list is immutable and can only contain unique elements, while a
set is mutable and can contain any type of data.
20. What is the output of the following Python code:
my_dict = {"name": "Alice", "age":25}
print(my_dict["name"])
a. “Alice” c. An error
b. 25 d. None of the above
21. What is a module in Python?
a. A collection of Python code that can be reused
b. A Python program that can be executed independently
c. A Python function that can be used to perform a specific task
d. All of the above
22. What is the difference between importing a module and using a
module in Python?
a. Importing a module makes its contents available to your Python
program, while using a module means calling a function or
accessing a variable from the module.
b. Using a module makes its contents available to your Python
program, while importing a module means calling a function or
accessing a variable from the module.
c. Importing a module means executing the module’s code, while
using a module means accessing the module’s functions and
variables.
d. Using a module means executing the module’s code, while
importing a module means accessing the module’s functions and
variables.
23. What is the output of the following Python code:
import math
print(math.sqrt(16))
a. 4 c. 16
b. 8 d. None of the above
24. What is a Python package?
a. A collection of Python modules
b. A Python program that can be executed independently
c. A Python function that can be used to perform a specific task
d. All of the above
25. What is the difference between a namespace and a scope in
Python?
a. A namespace is the set of all names that are defined in a program,
while a scope is the region of the program where a name is
accessible.
b. A scope is the set of all names that are defined in a program,
while a namespace is the region of the program where a name is
accessible.
c. A namespace is the region of the program where a name is
accessible, while a scope is the set of all names that are defined in
a program.
d. A scope is the region of the program where a name is accessible,
while a namespace is the set of all names that are defined in a
program.
26. What is the output of the following Python code:
def my_function():
global x
x =10
print(x)
x = 5
my_function()
a. 5 c. An error
b. 10 d. None of the above
27. What is a class in Python?
a. A blueprint for creating objects.
b. A collection of functions and variables.
c. A way to organize code into reusable modules.
d. All of the above
28. What is the difference between an instance and a class in Python?
a. A class is a blueprint for creating objects, while an instance is a
specific object that is created from a class.
b. An instance is a blueprint for creating objects, while a class is a
specific object that is created from an instance.
c. A class is a collection of functions and variables, while an
instance is a specific function or variable from a class.
d. An instance is a collection of functions and variables, while a
class is a specific function or variable from an instance.
29. What is the output of the following Python code:
class MyClass:
def __init__(self, name):
self.name = name
my_object = MyClass("Alice")
print(my_object.name)
a. “Alice”
b. MyClass
c. An error
d. None of the above
30. What is a Python exception?
a. An error that occurs during the execution of a Python program.
b. A way to handle errors in Python.
c. Both (a) and (b)
d. None of the above
31. What is the output of the following Python code?
try:
open("my_file.txt", "r")
except FileNotFoundError:
print("The file does not exist.")
If the file my_file.txt does not exist, the output of the code will be:
a. An error
b. “The file does not exist.”
c. None
d. Both (a) and (c)
32. What is the difference between a raise statement and an assert
statement in Python?
a. A raise statement is used to generate an exception, while an assert
statement is used to check for a condition and raise an exception
if the condition is not met.
b. An assert statement is used to generate an exception, while a raise
statement is used to check for a condition and raise an exception
if the condition is not met.
c. A raise statement is used to handle an exception, while an assert
statement is used to check for a condition and raise an exception
if the condition is met.
d. An assert statement is used to handle an exception, while a raise
statement is used to check for a condition and raise an exception
if the condition is not met.
33. What is the output of the following Python code:
def my_function(x):
if x < 0:
raise ValueError("x must be non-
negative.")
return x
print(my_function(-1))
The output of the code will be:
a. An error
b. -1
c. None
d. Both a and c
34. What is a Python decorator?
a. A function that can be used to modify the behavior of other
functions
b. A way to organize code into reusable modules
c. A way to add metadata to Python functions
d. All of the above
35. What is the difference between a staticmethod and a classmethod
in Python?
a. A staticmethod is a method that does not receive a self argument.
b. A classmethod is a method that receives a cls argument ,which
represent the class itself.
c. Both (a) and (b)
d. All of the above
36. Is the output of the following code correct:
def my_function():
return 1, 2, 3
x, y, z = my_function()
print(x)
print(y)
print(z)
The output of the code will be:
1
2
3
a. Yes
b. No
37. What is the difference between a list and a tuple in Python?
a. A list is mutable, while a tuple is immutable.
b. A list is ordered, while a tuple is unordered.
c. A list can contain any type of data, while a tuple can only contain
primitive data types.
d. All of the above
38. The output of the following Python code is correct:
my_list = [1, 2, 3, 4, 5]
my_list[2] =10
print(my_list)
The output of the code will be:
[1, 2,10, 4, 5]
a. No b. Yes
39. Is the output of the following code correct:
my_tuple = (1, 2, 3, 4, 5)
# my_tuple[2] =10 # This will generate an error
print(my_tuple)
The output of the code will be:
(1, 2, 3, 4)
a. Yes b. No
40. What is the difference between a zip() object and a dict() object in
Python?
a. A zip() object is a collection of pairs of elements, while a dict()
object is a collection of key-value pairs.
b. A zip() object is an ordered collection, while a dict() object is an
unordered collection.
c. A zip() object can contain any type of data, while a dict() object
can only contain primitive data types as keys.
d. All of the above
41. Is the output of the following Python code correct:
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
print(my_list[i])
The output of the code will be:
1
2
3
4
5
a. Yes b. No
42. What is the difference between a while loop and a for loop in
Python?
a. A while loop is used to iterate over a sequence of elements, while
a for loop is used to iterate over a range of numbers.
b. A while loop is used to iterate over a sequence of elements, while
a for loop is used to iterate over a collection of elements.
c. A while loop is used to iterate over a collection of elements,
while a for loop is used to iterate over a range of numbers.
d. A while loop is used to iterate over a collection of elements,
while a for loop is used to iterate over a sequence of elements.
43. Is the output of the following Python code correct?
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
The output of the code is:
0
2
3
4
5
a. Yes b. No
44. What is a list comprehension in Python?
a. A way to create a list from a sequence of elements
b. A way to filter the elements of a list
c. A way to map the elements of a list to new values
d. All of the above
45. What is the difference between a class and an object in Python?
a. A class is a blueprint for creating objects, while an object is
an instance of a class
b. A class is a collection of attributes and methods, while an
object is a single attribute or method
c. A class is a variable, while an object is a value
d. None of the above
46. Which of the following is NOT a Python data type:
a. Integer
b. String
c. List
d. Object
47. What is the difference between a list comprehension and a
generator expression in Python?
a. A list comprehension creates a list, while a generator expression
creates a generator object.
b. A list comprehension is evaluated immediately, while a generator
expression is evaluated lazily.
c. A list comprehension can only be used to filter and map the
elements of a list, while a generator expression can also be used
to transform the elements of a list.
d. All of the above
48. What is a lambda function in Python?
a. A function that is defined without a name
b. A function that is defined inside another function
c. A function that is passed as an argument to another function
d. All of the above
49. Which of the following is a Python built-in function?
a. my_function()
b. print()
c. input()
d. All of the above
50. Which of the following is a Python keyword?
a. def
b. class
c. for
d. All of the above
51. The output of the following Python code is correct:
my_list = [1, 2, 3, 4, 5]
sum_of_list = sum(my_list)
print(sum_of_list)
The output of the code will be:
15
a. Yes
b. No
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
53. What is the difference between a tuple and a set in Python?
a. A tuple is immutable, while a set is mutable.
b. A tuple is ordered, while a set is unordered.
c. A tuple can contain any type of data, while a set can only contain
primitive data types.
d. All of the above
54. What is the difference between a generator and a coroutine in
Python?
a. A generator is a function that yields one or more values, while a
coroutine is a function that can be suspended and resumed.
b. A generator is a function that can be used to create infinite
sequences, while a coroutine is a function that can be used to
create finite sequences.
c. A generator is a function that can be used to perform
asynchronous operations, while a coroutine is a function that can
be used to perform synchronous operations.
d. All of the above
55. What is the difference between a dictionary and a set in Python?
a. A dictionary is immutable, while a set is mutable.
b. A dictionary is ordered, while a set is unordered.
c. A dictionary can contain any type of data, while a set can only
contain primitive data types.
d. All of the above.
56. Which of the following is a Python module that can be used to
perform regular expressions?
a. re
b. math
c. random
d. os
57. What is the difference between a function and a class in Python?
a. A function is a collection of code that can be executed multiple
times, while a class is a blueprint for creating objects.
b. A function is a unit of code that performs a specific task, while a
class is a collection of related functions and data.
c. A function can only take arguments and return value
d. All of the above
58. What is the difference between a module and a package in
Python?
a. A module is a collection of Python code that can be reused, while
a package is a collection of Python modules.
b. A module is a Python file with the .py extension, while a package
is a directory containing Python modules and subdirectories.
c. A module can only be imported into one Python program at a
time, while a package can be imported into multiple Python
programs at the same time.
d. All of the above
59. Is the output of the following Python code correct:
import math
print(math.pi)
The output of the code will be:
3.141592653589793
a. Yes
b. No
60. What is the difference between a namespace and a scope in
Python?
a. A namespace is the set of all names that are defined in a program,
while a scope is the region of the program where a name is
accessible.
b. A scope is the set of all names that are defined in a program,
while a namespace is the region of the program where a name is
accessible.
c. A namespace is the region of the program where a name is
accessible, while a scope is the set of all names that are defined in
a program.
d. All of the above
61. What is the output of the following Python code:
def my_function():
global x
x =10
x = 5
my_function()
print(x)
a. 5 c. 10
b. Error d. None of the above
62. What is a Python class constructor?
a. A special method that is called when a new class object is
created.
b. A special method that is used to initialize a class object.
c. Both (a) and (b)
d. None of the above
63. What is the difference between a local variable and a global
variable?
a. A local variable is declared inside a function, while a global
variable is declared outside of any function.
b. A local variable is only available within the function in which it
is declared, while a global variable is available to all functions in
the program.
c. A local variable is automatically initialized to zero, while a global
variable must be explicitly initialized.
d. All of the above
64. What is a Python exception?
a. An error that occurs during the execution of a Python program.
b. A way to handle errors in Python.
c. Both (a) and (b)
d. None of the above
65. What is the difference between a regular expression and a string?
a. A regular expression is a sequence of characters that defines a
search pattern, while a string
b. is a sequence of characters that represents text.
c. A regular expression is a string that contains special characters,
while a string is a string that does not contain special characters.
d. A regular expression is a compiled string, while a string is an
uncompiled string.
e. All of the above
66. What is the output of the following Python code:
import re
my_string = "Hello, world!"
match = re.search(r"world", my_string)
if match:
print(match.group())
else:
print("The string does not contain the word
'world'.")
The output of the code will be:
a. world c. Error
b. Hello,world d. None of the above
67. What is the difference between a function and a method in
Python?
a. A function is a global function, while a method is a function that
is defined inside a class.
b. A function can be called directly, while a method must be called
on an object.
c. Both (a) and (b)
d. None of the above
68. What is the difference between a class attribute and an instance
attribute in Python?
a. A class attribute is an attribute that is shared by all objects of a
class, while an instance attribute is an attribute that is unique to
each object of a class.
b. A class attribute is an attribute that is defined outside of a class,
while an instance attribute is an attribute that is defined inside of
a class.
c. A class attribute is a global attribute, while an instance attribute is
a local attribute.
d. None of the above
69. What is the difference between a module and a package in
Python?
a. A module is a collection of Python code that can be reused, while
a package is a collection of Python modules.
b. A module is a Python file with the .py extension, while a package
is a directory containing Python modules and subdirectories.
c. A module can only be imported into one Python program at a
time, while a package can be imported into multiple Python
programs at the same time.
d. All of the above
70. What is the difference between a namespace and a scope in
Python?
a. A namespace is the set of all names that are defined in a program,
while a scope is the region of the program where a name is
accessible.
b. A scope is the set of all names that are defined in a program,
while a namespace is the region of the program where a name is
accessible.
c. A namespace is the region of the program where a name is
accessible, while a scope is the set of all names that are defined in
a program.
d. All of the above
71. Which of the following is NOT a valid way to open a file in
Python?
a. open(“file.txt”, mode=”read”)
b. open(“file.txt”, “r”)
c. open(“file.txt”, mode=”w”)
d. open(“file.txt”)
72. What is a Python class constructor?
a. A special method that is called when a new class object is
created.
b. A special method that is used to initialize a class object.
c. Both a and b
d. None of the above
73. What is the difference between a regular expression and a string?
a. A regular expression is a sequence of characters that defines a
search pattern, while a string is a sequence of characters that
represents text.
b. A regular expression is a string that contains special characters,
while a string is a string that does not contain special characters.
c. A regular expression is a compiled string, while a string is an
uncompiled string.
d. All of the above
74. What is the difference between a function and a method in
Python?
a. A function is a global function, while a method is a function that
is defined inside a class.
b. A function can be called directly, while a method must be called
on an object.
c. Both (a) and (b)
d. None of the above
75. Which of the following is a control statement in Python?
a. int
b. print()
c. if
d. all()
76. What is the output of the following code:
x =10
while x > 0:
print(x)
x -= 1
a. 10 9 8 7 6 5 4 3 2 1
b. 10
c. Infinite loop
d. None of the above
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
78. What is the output of the following code:
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i % 2 == 0:
print(i)
a. 1 2 3 4 5
b. 2 4
c. 1 3 5
d. None 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.
80. What is the output of the following code:
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 3:
break
print(i)
a. 1 2 3
b. 1 2
c. 1
d. None of the above
81. What is the output of the following code?
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 3:
continue
print(i)
a. 1 2 3 4 5
b. 1 2 4 5
c. 1 4 5
d. None of the above
82. Which of the following is the correct syntax for a nested if
statement in Python?
a. if a >10 and b < 5:
b. if a >10: if b < 5:
c. if a >10 and b < 5: if c >15:
d. All of the above
83. What is the output of the following code?
a =10
b=5
if a > b:
print(“a is greater than b”)
elif a < b:
print(“a is less than b”)
else:
print(“a is equal to b”)
a. a is greater than b
b. a is less than b
c. a is equal to b
d. None of the above
84. Which of the following is a jump statement in Python?
a. if c. break
b. for d. All of the above
85. Which of the following is the correct syntax for a pass statement in
Python?
a. pass c. # pass
b. pass() d. All of the above
86. Which of the following is a valid infinite loop in Python?
a. while True:
b. for i in range(10):
c. for i in range(10000): if i % 2 == 0: print(i)
d. All of the above
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
89. What is the output of the following code:my_list = [1, 2,
3, 4, 5]
for i in my_list:
if i % 2 == 0:
continue
print(i)
a. 1 3 5 c. 1 2 3 4 5
b. 2 4 d. None of the above
90. What is the output of the following code:
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i % 2 == 0:
break
print(i)
a. 1
b. 1 2
c. 1 2 3 4 5
d. None of the above
91. What is the output of the following code:
1 + 2 * 3
a. 7 c. 5
b. 6 d. 4
92. What is the output of the following code:
10 // 3
a. 3 c. 3.0
b. 3.33 d. 4
93. What is the output of the following code:10 % 3
a. 1
b. 3.33
c. 3.0
d. 0
94. What is the output of the following code:
10 ** 2
a. 100
b. 10
c. 20
d. 1
95. What is the output of the following code:
"10" + 2
a. “102”
b. 12
c. TypeError
d. None of the above
96. What is the output of the following code:True and False
a. True
b. False
c. TypeError
d. None of the above
97. What is the output of the following code:True or False
a. True
b. False
c. TypeError
d. None of the above
98. What is the output of the following code:
not True
a. True
b. False
c. TypeError
d. None of the above
99. What is the output of the following code:
10// 3 == 3
a. True
b. False
c. TypeError
d. None of the above
100. What is the output of the following code:
10 % 3 == 1
a. True
b. False
c. TypeError
d. None of the above
101. What is the output of the following code:
10 ** 2 ==100
a. True
b. False
c. TypeError
d. None of the above
102. What is the output of the following code:
"10" + 2 == "12"
a. True
b. False
c. TypeError
d. None 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
104. What is the output of the following code:
True or False == True
a. True
b. False
c. TypeError
d. None of the above
105. What is the output of the following code:
not True == False
a. True
b. False
c. TypeError
d. None of the above
106. What is the output of the following code:
10 > 3 and 3 > 1
a. True
b. False
c. TypeError
d. None of the above
107. What is the output of the following code:
10 > 3 or 3 > 1
a. True
b. False
c. TypeError
d. None of the above
108. What is a module in Python?
a. A self-contained collection of Python code
b. A function in Python
c. A variable in Python
d. A data type in Python
109. What is the benefit of using modules in Python?
a. Modules make your code more organized and reusable
b. Modules allow you to access functions and variables from other
modules
c. Modules improve the performance of your code
d. All of the above
110. How do you import a module in Python?
a. Use the import statement
b. Use the include statement
c. Use the require statement
d. None of the above
111. What is the difference between a built-in module and a third-party
module?
a. Built-in modules are included with the Python interpreter, while
third-party modules are installed separately
b. Built-in modules are faster than third-party modules
c. Built-in modules are less flexible than third-party modules
d. All of the above
112. Which of the following is a built-in module in Python?
a. math
b. numpy
c. pandas
d. requests
113. Which of the following is a third-party module in Python?
a. All of the above
b. numpy
c. pandas
d. requests
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
115. How do you import a specific function or variable from a module?
a. Use the from statement
b. Use the import statement
c. Use the include statement
d. Use the require statement
116. What is a namespace in Python?
a. A namespace is a region of a program’s memory where names
are mapped to objects
b. A namespace is a collection of modules
c. A namespace is a type of variable
d. All of the above
117. What is the difference between a global namespace and a local
namespace?
a. The global namespace is the namespace for the entire program,
while the local namespace is the namespace for a specific
function or module
b. The global namespace is faster than the local namespace
c. The global namespace is less flexible than the local namespace
d. All of the above
118. Which of the following is a valid way to import a module called
my_module?
a. import my_module
b. include my_module
c. require my_module
d. All of the above
119. Which of the following is a valid way to import a specific function
called add() from a module called my_module?
a. from my_module import add
b. import my_module.add
c. include my_module.add
d. require my_module.add
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
121. Which of the following is a valid way to check if a module exists?
a. if my_module in sys.modules:
b. if my_module is not None:
c. if my_module:
d. All of the above
122. Which of the following is a valid way to reload a module?
a. importlib.reload(my_module)
b. reload(my_module)
c. my_module.reload()
d. None of the above
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
124. Which of the following is a good practice for writing modules?
a. Use descriptive names for modules and functions
b. Document your modules and functions
c. Use a consistent coding style
d. All of the above
125. What is the __init__() method used for?
a. The __init__() method is used to initialize a module
b. The __init__() method is used to initialize a class
c. The __init__() method is used to initialize a function
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
129. Which of the following is a valid way to create a new module?
a. Create a new file with a .py extension
b. Import a module that does not exist
c. Use the importlib.util.module_from_source() function
d. All of the above
130. Which of the following is a valid way to share data between
modules?
a. Use global variables
b. Use the importlib.util.module_from_source() function
c. Use a database
d. All of the above
131. Which of the following is a good practice for using modules?
a. Avoid using global variables
b. Use descriptive names for modules and functions
c. Document your modules and functions
d. All of the above
132. Which of the following is a common mistake to make when using
modules?
a. Importing the same module multiple times
b. Not documenting modules and functions
c. Using global variables
d. All of the above
133. What is the difference between a built-in function and a function
defined in a module?
a. Built-in functions are faster than functions defined in modules.
b. Built-in functions are less flexible than functions defined in
modules.
c. Built-in functions are included with the Python interpreter, while
functions defined in modules are not.
d. All of the above
134. What is the difference between a public function and a private
function in a module?
a. A public function can be accessed from outside the module, while
a private function cannot.
b. A public function is faster than a private function.
c. A public function is less flexible than a private function.
d. None of the above
135. How do you define a private function in a module?
a. Use a double underscore prefix, for example __add__(self, other)
b. Use a single underscore prefix, for example _add__(self, other)
c. Use a private keyword, for example private def add__(self, other)
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.
137. What is the benefit of using private functions?
a. Private functions can be used to implement internal functionality
of a module without exposing it to the outside world.
b. Private functions can improve the performance of a module by
hiding unnecessary details from the caller.
c. Private functions can make a module more readable and
maintainable.
d. All of the above
138. What is the difference between a module variable and a function
variable?
a. A module variable is defined at the top level of a module, while a
function variable is defined inside a function.
b. A module variable can be accessed from anywhere in the module,
while a function variable can only be accessed from inside the
function where it is defined.
c. A module variable is faster than a function variable.
d. All of the above
139. How do you define a module variable?
a. Simply assign a value to it, for example my_variable = 1
b. Use the global keyword, for example global my_variable
c. Use a module_variable keyword, for example module_variable
my_variable = 1
d. None of the above
140. How do you access a module variable from inside a function?
a. Use the dot notation, for example my_module.my_variable
b. Use the global keyword, for example global
my_module.my_variable
c. Use the getattr() function, for example getattr(my_module,
‘my_variable’)
d. Any of the above
141. How do you write a documentation string for a module?
a. Triple-quote (```) the documentation string and place it at the top
of the module file.
b. Use a __doc__ keyword, for example __doc__ = ‘This is a
documentation string for my module.
c. You do not need to write a documentation string for a module.
d. None of the above
142. What is the importlib module?
a. The importlib module provides a dynamic import system for
Python.
b. The importlib module can be used to import modules, reload
modules, and remove modules from the global namespace.
c. The importlib module is part of the Python standard library.
d. All of the above
143. What is the inspect module?
a. The inspect module provides functions for inspecting Python
objects, such as modules, functions, and classes.
b. The inspect module can be used to get the source code of a
function, the arguments to a function, and the docstring for a
function.
c. The inspect module is part of the Python standard library
d. All of the above.
144. What is the sys module?
a. The sys module provides information about the current Python
environment, such as the Python version, the system path, and the
current working directory.
b. The sys module can be used to exit the Python interpreter, set the
global namespace, and get the list of all imported modules.
c. The sys module is part of the Python standard library.
d. All of the above.
145. What is the pathlib module
a. The pathlib module provides a platform-independent way to work
with file paths
b. The pathlib module can be used to create, join, and split file
paths.
c. The pathlib module is part of the Python standard library.
d. All of the above
146. What is the os module?
a. The os module provides functions for interacting with the
operating system, such as creating and deleting files, running
processes, and getting environment variables.
b. The os module is part of the Python standard library.
c. Both of the above.
147. Which of the following is a good practice for writing modules?
a. Use descriptive names for modules, functions, and variables.
b. Document your modules, functions, and variables.
c. Use a consistent coding style.
d. All of the above.
148. Which of the following is a common mistake to make when using
modules?
a. Importing the same module multiple times.
b. Not documenting modules, functions, and variables.
c. Using global variables
d. All of the above.
149. What is a good way to test modules?
a. Write unit tests for your modules.
b. Use a code coverage tool to measure the coverage of your unit
tests.
c. Both of the above.
150. What is a good way to distribute modules?
a. Use a package manager such as PIP.
b. Publish your modules to a public repository such as PyPI.
c. Both of the above.
151. Which of the following is a popular Python package manager?
a. PIP
b. Conda
c. Maven
d. Both (a) and (b)
152. Which of the following is a popular Python web framework?
a. Django c. Pyramid
b. Flask d. All of the above
153. Which of the following is a popular Python machine learning
library?
a. NumPy c. Scikit-learn
b. Pandas d. All of the above
154. Which of the following is a good resource for learning more about
Python modules?
a. The Python documentation
b. The Python subreddit
c. Stack Overflow
d. All of the above
155. What is a library in Python?
a. A collection of pre-written code that can be used in your own
Python programs
b. A way to organize your Python code into modules and packages
c. A way to import code from other Python programs
d. All of the above
156. What are the benefits of using libraries in Python?
a. Libraries save you time and effort by providing pre-written code
that you can use in your own programs.
b. Libraries make your code more readable and maintainable by
organizing it into modules and packages.
c. Libraries make it easy to share your code with others by allowing
you to import code from other Python programs.
d. All of the above
157. What are some examples of popular Python libraries?
a. NumPy, Pandas, and Matplotlib for scientific computing and data
visualization.
b. Django and Flask for web development.
c. requests, BeautifulSoup, and Selenium for web scraping.
d. All of the above.
158. How do you import a library in Python?
a. Use the import statement.
b. Use the from statement.
c. Both (a) and (b).
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
160. What is a good practice for using libraries in Python?
a. Use descriptive names for the libraries that you import.
b. Document your code to explain how you are using the libraries
that you import.
c. Use a consistent coding style
d. All of the above
161. What is the pip command used for?
a. To install Python libraries.
b. To update Python libraries.
c. To uninstall Python libraries.
d. All of the above
162. What is the virtualenv command used for?
a. To create a virtual environment for Python development.
b. To activate a virtual environment.
c. To deactivate a virtual environment.
d. All of the above
163. What is the difference between a standard library and a third-
party library?
a. A standard library is a library that comes pre-installed with
Python.
b. A third-party library is a library that is developed and maintained
by someone other than the Python core team.
c. Both (a) and (b)
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.
166. What are the five basic data types in Python?
a. Numbers, strings, lists, tuples, and dictionaries
b. Numbers, strings, lists, dictionaries, and sets
c. Numbers, strings, lists, sets, and tuples
d. Numbers, strings, lists, dictionaries, and sets
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
171. Which of the following is a valid Python data type?
a. Boolean
b. integer
c. float
d. All of the above
172. 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
173. What is the difference between a local variable and a global
variable?
a. A local variable is a variable that is defined within a function,
while a global variable is a variable that is defined outside of any
function.
b. Local variables are faster than global variables.
c. Local variables are more flexible than global variables.
d. None of the above.
174. What is the best way to avoid using global variables?
a. Pass arguments to functions instead of using global variables.
b. Use return values from functions to get the data that you need.
c. Use modules and classes to organize your code.
d. All of the above.
175. What is the best way to document your code?
a. Use comments to explain your code.
b. Use docstrings to explain your functions and classes.
c. Use type hints to specify the data types of your variables and
function arguments.
d. All of the above.
176. What is the best way to test your code?
a. Write unit tests for your code.
b. Use a code coverage tool to measure the coverage of your unit
tests.
c. Both (a) and (b).
d. None of the above.
177. What is the best way to debug your code?
a. Use the Python debugger.
b. Use print statements to output the values of your variables.
c. Use logging to track the execution of your code.
d. All 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
179. What are some examples of primitive data types in Python?
a. int, float, bool, str
b. list, tuple, dict, set
c. class, function, module, package
d. None of the above
180. What are some examples of non-primitive data types in Python?
a. list, tuple, dict, set
b. class, function, module, package
c. Both (a) and (b)
d. None of the above
181. What is the difference between a sequence data type and a
mapping data type?
a. Sequence data types store data in a linear order, while mapping
data types store data in key-value pairs.
b. Sequence data types are mutable, while mapping data types are
immutable.
c. Sequence data types are faster than mapping data types.
d. None of the above
182. What are some examples of sequence data types in Python?
a. list, tuple, str
b. dict, set
c. class, function, module
d. None of the above.
183. What are some examples of mapping data types in Python?
a. dict
b. set
c. class, function, module
d. None of the above.
184. What is the best way to choose the right data type for your needs?
a. Consider the type of data that you need to store and how you
need to manipulate it.
b. Think about the performance and memory requirements of your
application.
c. Choose a data type that is easy to read and understand.
d. All of the above
185. What is the difference between a class and an object?
a. A class is a blueprint for creating objects, while an object is an
instance of a class.
b. Classes are mutable, while objects are immutable.
c. Classes are faster than objects.
d. None of the above
186. What is the difference between a method and a function?
a. Methods are functions that are defined within a class, while
functions are functions that are defined outside of any class.
b. Methods are faster than functions.
c. Methods are more flexible than functions.
d. None of the above
187. What is the difference between a module and a package?
a. A module is a single file, while a package is a collection of
modules.
b. Modules are faster than packages.
c. Modules are more flexible than packages.
d. None of the above
188. What is the difference between a namespace and a scope?
a. A namespace is a collection of names and their associated values,
while a scope is the region of code in which a name is visible.
b. Namespaces are faster than scopes.
c. Namespaces are more flexible than scopes.
d. None of the above
189. What is the best way to avoid name collisions?
a. Use descriptive names for your variables and functions.
b. Use namespaces to organize your code.
c. Use type hints to specify the data types of your variables and
function arguments.
d. All of the above
190. What is the difference between a type hint and a cast?
a. A type hint is a suggestion to the Python interpreter about the
data type of a variable, while a cast is a way to force the Python
interpreter to convert a variable to a specific data type.
b. Type hints are faster than casts.
c. Type hints are more flexible than casts.
d. None of the above.
191. What is the best way to remove an element from a set?
a. Use the remove() method.
b. Use the pop() method.
c. Both (a) and (b).
d. None of the above
192. What is the best way to check if an element is in a set?
a. Use the in operator.
b. Use the not in operator.
c. Both (a) and (b).
d. None 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
197. What is the best way to iterate over a set?
a. Use a for loop
b. Use a while loop
c. Both (a) and (b)
d. None of the above
198. What is the best way to copy a set?
a. Use the copy() method
b. Use the deepcopy() method
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
200. What is the difference between a literal and an expression?
a. A literal is a value that is written directly into the code, while an
expression is a combination of literals, operators, and variables
that evaluates to a value.
b. Literals are faster than expressions.
c. Literals are more flexible than expressions.
d. None of the above
201. What is the difference between a number and a string?
a. A number is a value that can be used in mathematical operations,
while a string is a sequence of characters.
b. Numbers are immutable, while strings are mutable.
c. Numbers are faster than strings.
d. All of the above
202. What is the difference between a list and a tuple?
a. A list is mutable, while a tuple is immutable.
b. A list can store any type of data, while a tuple can only store
elements of the same type.
c. Lists are faster than tuples.
d. All of the above.
203. What is the difference between a dictionary and a set?
a. A dictionary stores key-value pairs, while a set store unique
elements.
b. Dictionaries are mutable, while sets are immutable.
c. Dictionaries are faster than sets.
d. All 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
207. What is the difference between a local variable and a global
variable?
a. A local variable is within a function, while a global variable is
outside of any function.
b. Local variables are faster than global variables.
c. Local variables are more flexible than global variables.
d. None of the above
208. What is the best way to avoid using global variables?
a. Pass arguments to functions instead of using global variables.
b. Use return values from functions to get the data that you need.
c. Use modules and classes to organize your code.
d. All of the above
209. What is the best way to document your code?
a. Use comments to explain your code.
b. Use docstrings to explain your functions and classes.
c. Use type hints to specify the data types of your variables and
function arguments.
d. All of the above
210. What is the best way to test your code?
a. Write unit tests for your code.
b. Use a code coverage tool to measure the coverage of your unit
tests.
c. Both (a) and (b)
d. None of the above
211. What is the best way to debug your code?
a. Use the Python debugger.
b. Use print statements to output the values of your variables.
c. Use logging to track the execution of your code.
d. All 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
214. What is the difference between a frozenset and a set?
a. A frozenset is immutable, while a set is mutable.
b. Frozensets are faster than sets.
c. Frozensets are more flexible than sets.
d. None of the above
215. What is the difference between a bytearray and a bytes object?
a. A bytearray is mutable, while a bytes object is immutable.
b. Bytearrays are faster than bytes objects.
c. Bytearrays are more flexible than bytes objects.
d. None of the above.
216. What is the difference between a memoryview and a bytearray?
a. A memoryview is a view into a buffer of bytes, while a bytearray
is a mutable array of bytes.
b. Memoryviews are faster than bytearrays.
c. Memoryviews are more flexible than bytearrays.
d. None of the above
217. What is the best way to check if a variable is None?
a. Use the is operator
b. Use the == operator
c. Both (a) and (b)
d. None of the above
218. What is the best way to check if a variable is a string?
a. Use the type() function.
b. Use the isinstance() function.
c. Both (a) and (b).
d. None of the above
219. What is the best way to check if a variable is a list?
a. Use the type() function.
b. Use the isinstance() function.
c. Both (a) and (b)
d. None of the above
220. What is the best way to check if a variable is a tuple?
a. Use the type() function
b. Use the isinstance() function
c. Both (a) and (b)
d. None of the above
221. What is the best way to check if a variable is a dictionary?
a. Use the type() function
b. Use the isinstance() function
c. Both (a) and (b)
d. None of the above
222. What is the best way to check if a variable is a set?
a. Use the type() function
b. Use the isinstance() function
c. Both (a) and (b)
d. None of the above
223. What is the best way to convert a string to an integer?
a. Use the int() function.
b. Use the float() function.
c. Use the str() function.
d. None of the above
224. What is the best way to convert an integer to a float?
a. Use the int() function
b. Use the float() function
c. Use the str() function
d. None of the above
225. What is the best way to convert a string to a list?
a. Use the list() function
b. Use the tuple() function
c. Use the str() function
d. None of the above
226. What is the best way to convert a list to a tuple?
a. Use the list() function
b. Use the tuple() function
c. Use the str() function
d. None of the above
227. What is the best way to convert a tuple to a list?
a. Use the list() function
b. Use the tuple() function
c. Use the str() function
d. None of the above
228. What is the best way to convert a dictionary to a list?
a. Use the list() function
b. Use the dict() function
c. Use the str() function
d. None of the above
229. What is the best way to convert a list to a dictionary?
a. Use the list() function
b. Use the dict() function
c. Use the str() function
d. None of the above
230. What is the best way to sort a list?
a. Use the sort() method
b. Use the sorted() function
c. Both (a) and (b)
d. None of the above
231. What is the best way to reverse a list?
a. Use the reverse() method
b. Use the reversed() function
c. Both (a) and (b)
d. None of the above
232. What is the best way to find the maximum value in a list?
a. Use the max() function
b. Use the min() function
c. Both (a) and (b)
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
234. What is the best way to check if a value is in a list?
a. Use the in operator
b. Use the not in operator
c. Both (a) and (b)
d. None of the above
235. What is the best way to remove a value from a list?
a. Use the remove() method.
b. Use the pop() method
c. Both (a) and (b)
d. None of the above
236. What is the best way to insert a value into a list?
a. Use the insert() method.
b. Use the append() method
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
243. What is the best way to convert a list to a string?
a. Use the join() method
b. Use the str() function
c. Both (a) and (b)
d. None of the above
244. What is the best way to split a string into a list?
a. Use the split() method
b. Use the str() function
c. Both (a) and (b)
d. None of the above
245. What is the best way to check if a dictionary is empty?
a. Use the len() function
b. Use the is not None operator
c. Both (a) and (b)
d. None of the above
246. What is the best way to get the keys of a dictionary?
a. Use the keys() method
b. Use the values() method
c. Both (a) and (b)
d. None of the above
247. What is the best way to get the values of a dictionary?
a. Use the keys() method
b. Use the values() method
c. Both (a) and (b)
d. None of the above
248. What is the best way to check if a key is present in a dictionary?
a. Use the in operator
b. Use the not in operator
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 a 51 a 101 a 151 d 201 a
2 a 52 a 102 b 152 d 202 d
3 d 53 b 103 a 153 d 203 d
4 d 54 d 104 a 154 d 204 c
5 b 55 c 105 a 155 d 205 d
6 a 56 a 106 a 156 d 206 a
7 a 57 b 107 a 157 d 207 a
8 a 58 a 108 a 158 c 208 d
9 a 59 a 109 d 159 a 209 d
10 d 60 a 110 a 160 d 210 c
11 a 61 d 111 a 161 d 211 d
12 a 62 c 112 a 162 d 212 d
13 b 63 d 113 a 163 c 213 a
14 c 64 c 114 d 164 d 214 a
15 a 65 a 115 a 165 c 215 a
16 a 66 a 116 a 166 a 216 a
17 d 67 c 117 a 167 a 217 a
18 a 68 a 118 a 168 d 218 b
19 a 69 a 119 a 169 d 219 b
20 a 70 a 120 b 170 c 220 b
21 a 71 a 121 a 171 d 221 b
22 a 72 c 122 a 172 a 222 b
23 a 73 a 123 a 173 a 223 a
24 a 74 c 124 d 174 d 224 b
25 a 75 c 125 a 175 d 225 a
26 b 76 a 126 b 176 c 226 b
27 d 77 d 127 d 177 d 227 a
28 a 78 b 128 a 178 a 228 a
29 a 79 a 129 d 179 a 229 b
30 c 80 b 130 c 180 c 230 c
31 b 81 c 131 d 181 a 231 c
32 a 82 d 132 d 182 a 232 a
33 a 83 a 133 c 183 a 233 b
34 d 84 c 134 a 184 d 234 c
35 c 85 a 135 a 185 a 235 c
36 a 86 a 136 b 186 a 236 c
37 a 87 d 137 d 187 a 237 c
38 b 88 d 138 b 188 a 238 c
39 b 89 a 139 a 189 d 239 c
40 a 90 a 140 d 190 a 240 b
41 a 91 a 141 a 191 a 241 a
42 d 92 a 142 d 192 c 242 a
43 b 93 a 143 d 193 c 243 c
44 d 94 a 144 d 194 c 244 a
45 a 95 c 145 d 195 c 245 a
46 d 96 b 146 c 196 a 246 a
47 d 97 a 147 d 197 a 247 b
48 d 98 b 148 d 198 a 248 c
49 d 99 a 149 c 199 c 249 b
50 d 100 a 150 c 200 a 250 b
CHAPTER 3
Data types, Operators and
Expressions
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.
Multiple choice questions
1. What maximum value can be stored in an int in Python?
a. 2^32 - 1 c. 2^15 - 1
b. 2^63 - 1 d. 2^7 – 1
2. Which of the following is an immutable data type in Python?
a. List c. Set
b. Tuple d. Dictionary
3. What is the data type of the result of the expression 5 / 2 in
Python?
a. int c. str
b. float d. bool
4. How do you define an empty list in Python?
a. empty_list = [] c. empty_list = ()
b. empty_list = {} d. empty_list = [None]
5. Which of the following is not a valid variable name in Python?
a. my_variable c. variable_1
b. 1st_variable d. variable
6. In Python, what does the len() function return for a string?
a. Number of words
b. Number of characters
c. Number of lines
d. Number of vowels
7. What is the output of print(type(3.14)) in Python?
a. int c. str
b. float d. bool
8. Which of the following is a mutable data type in Python?
a. Tuple
b. List
c. String
d. Set
9. What does the ord() function do in Python?
a. Returns the next number in a sequence
b. Returns the Unicode code of a character
c. Returns the binary representation of a number
d. Returns the square root of a number
10. How do you convert a string to lowercase in Python?
a. str.lower()
b. str.upper()
c. str.capitalize()
d. str.title()
11. What is the purpose of the chr() function in Python?
a. Returns the character at a specified index
b. Converts a string to lowercase
c. Returns the Unicode character for a given code
d. Checks if a character is a digit
12. Which of the following is a valid way to create an empty tuple in
Python?
a. empty_tuple = ()
b. empty_tuple = []
c. empty_tuple = None
d. empty_tuple =
13. What is the output of print(bool([])) in Python?
a. True c. None
b. False d. Error
14. What is the purpose of the strip() method in Python?
a. Removes leading and trailing spaces from a string
b. Splits a string into a list
c. Joins elements of a list into a string
d. Converts a string to uppercase
15. Which of the following is a valid way to create a set in Python?
a. my_set = {1, 2, 3}
b. my_set = [1, 2, 3]
c. my_set = (1, 2, 3)
d. my_set = {1: ‘one’, 2: ‘two’}
16. What is the output of print("Hello" + 3) in Python?
a. Hello3 c. Error
b. HelloHelloHello d. None
17. What is the result of the expression 5 % 2 in Python?
a. 2.5 c. 1
b. 2 d. 1.5
18. How do you check the length of a list in Python?
a. length(list) c. len(list)
b. size(list) d. list.length()
19. What is the data type of the result of the expression True + 5 in
Python?
a. Int c. bool
b. float d. str
20. Which of the following is a mutable sequence type in Python?
a. Tuple c. String
b. List d. Set
21. What is the output of print(3 * 'abc') in Python?
a. abcabc c. Error
b. abcabcabc d. None
22. What does the pop() method do in Python?
a. Adds an element to the end of a list
b. Removes and returns the last element of a list
c. Removes and returns the first element of a list
d. Retrieves the element at a specified index
23. What is the result of the expression int("42") in Python?
a. 42 c. Error
b. “42” d. 0
24. How do you concatenate two lists in Python?
a. list1.concat(list2)
b. list1 + list2
c. list1.extend(list2)
d. All of the above
25. What is the purpose of the append() method in Python?
a. Adds an element to the beginning of a list
b. Adds an element to the end of a list
c. Removes the last element of a list
d. Removes the first element of a list
26. Which of the following is a valid way to create a dictionary in
Python?
a. my_dict = {1, ‘one’, 2, ‘two’}
b. my_dict = [(1, ‘one’), (2, ‘two’)]
c. my_dict = {1: ‘one’, 2: ‘two’}
d. All of the above
27. What is the result of the expression 2 ** 3 in Python?
a. 6 c. 8
b. 9 d. 5
28. How do you check if a value is present in a list in Python?
a. value.exist(list)
b. value in list
c. list.has_value(value)
d. list.contains(value)
29. What is the output of print(10 / 3) in Python?
a. 3.3333333333333335
b. 3.0
c. 3
d. 3.333
30. Which of the following is not a valid way to create a dictionary in
Python?
a. my_dict = dict([(1, ‘one’), (2, ‘two’)])
b. my_dict = {1: ‘one’, 2: ‘two’}
c. my_dict = {1, ‘one’, 2, ‘two’}
d. my_dict = {1: ‘one’, ‘two’: 2}
31. What is the result of the expression abs(-5) in Python?
a. 5 c. 0
b. -5 d. 1
32. What is the purpose of the enumerate() function in Python?
a. Returns the index of an element in a list
b. Returns the sum of all elements in a list
c. Returns both the index and value of elements in a list
d. Returns the average of all elements in a list
33. Which of the following is a valid way to create a range object in
Python?
a. range(5)
b. range(1, 5)
c. range(1, 5, 2)
d. All of the above
34. What is the output of print("apple" > "banana") in
Python?
a. True c. Error
b. False d. None
35. What is the output of print(type(range(5))) in Python?
a. int c. list
b. float d. range
36. What is the purpose of the count() method in Python?
a. Counts the number of elements in a list
b. Counts the occurrences of a specified element
c. Counts the number of unique elements in a list
d. Counts the number of elements in a tuple
37. Which of the following is a valid way to create a constant in
Python?
a. CONSTANT = 10
b. constant(10)
c. const = 10
d. All of the above
38. What is the result of the expression list("Python") in
Python?
a. “Python”
b. [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
c. (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
d. Error
39. What is the output of print("Python".find("th")) in
Python?
a. -1 c. 2
b. 0 d. 3
40. How do you check if a string contains only alphabetic characters
in Python?
a. string.is_alpha()
b. string.is_alpha
c. string.isalpha()
d. is_alpha(string)
41. What is the result of the expression 10 // 3 in Python?
a. 3
b. 3.0
c. 3
d. 3.3333333333333335
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’}
43. What is the output of print("Python"[-2:]) in Python?
a. On c. on
b. th d. thon
44. How do you convert a string to a list of characters in Python?
a. list(string) c. string.split()
b. string.to_list() d. list(string)
45. What is the output of print("apple" < "banana") in
Python?
a. True c. Error
b. False d. None
46. What is the result of the expression 5 + 3 * 2 in Python?
a. 16 c. 11
b. 26 d. 15
47. How do you check if a string contains only numeric characters in
Python?
a. string.isnumeric()
b. string.isdigit()
c. string.isnumeric
d. isnumeric(string)
48. What is the purpose of the clear() method in Python?
a. Removes the last element of a list
b. Removes all elements from a list
c. Adds an element to the end of a list
d. Removes the first element of a list
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]
50. What is the result of the expression 5 + 3 in Python?
a. 8 c. 53
b. 15 d. Error
51. Which operator is used for exponentiation in Python?
a. ** c. ^
b. ^ d. ex
52. What is the value of 7 // 2 in Python?
a. 3.5 c. 4
b. 3 d. 2.5
53. What does the % operator do in Python?
a. Division c. Exponentiation
b. Modulus d. Multiplication
54. What is the result of the expression 7 / 2 in Python?
a. 3.5 c. 4
b. 3 d. 2.5
55. Which operator is used for floor division in Python?
a. / c. %
b. // d. None of the above
56. What is the result of the expression 3 * 2 ** 2 in Python?
a. 12 c. 24
b. 18 d. 9
57. Which operator is used for string concatenation in Python?
a. + c. /
b. * d. –
58. What is the result of the expression 2 + 3 * 4 in Python?
a. 20 c. 18
b. 14 d. 32
59. Which of the following is the correct way to comment a single line
in Python?
a. // This is a comment
b. # This is a comment
c. /* This is a comment */
d. -- This is a comment
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
73. Which operator is used for exponentiation in Python 2.x?
a. ** c. pow()
b. ^ d. ex
74. What is the result of the expression True or False in Python?
a. True c. None
b. False d. Error
75. What is the result of the expression not (False and True) in
Python?
a. True c. None
b. False d. Error
76. Which of the following is a valid way to create a list of numbers
from 1 to 5 in Python?
a. [1, 2, 3, 4, 5]
b. list(1, 5)
c. range(1, 5)
d. All of the above
77. What is the result of the expression 5 != '5' in Python?
a. True c. None
b. False d. Error
78. Which operator is used for bitwise AND in Python?
a. & c. ^
b. | d. ~
79. Which of the following is a valid way to create a tuple in Python?
a. my_tuple = (1, 2, 3)
b. my_tuple = [1, 2, 3]
c. my_tuple = {1, 2, 3}
d. my_tuple = 1, 2, 3
80. What is the result of the expression 3 // 2 in Python?
a. 1.5 c. 2
b. 1 d. 1.0
81. Which operator is used for string repetition in Python?
a. + c. /
b. * d. –
82. What is the result of the expression 2.5 // 2 in Python?
a. 1.25 c. 2
b. 1 d. 1.0
83. What is the result of the expression 5 / 2 in Python 2.x?
a. 2.5 c. 2.0
b. 2 d. 2.5
84. Which operator is used for string slicing in Python?
a. : c. ..
b. :: d. ->
85. What is the result of the expression 10 % 3 in Python?
a. 3.3333333333333335
b. 3
c. 1
d. 3.333
86. What is the result of the expression 2 ** 3 in Python 2.x?
a. 6 c. 8
b. 9 d. 5
87. What is the result of the expression 10 + 3.0 in Python?
a. 13 c. 10.3
b. 13.0 d. Error
88. What is the result of the expression 2 + 3 * 4 in Python 2.x?
a. 20 c. 18
b. 14 d. 32
89. Which of the following is a valid way to check if a number is odd
in Python?
a. x % 2 == 0 c. isodd(x)
b. x.is_odd() d. All of the above
90. What is the result of the expression True and False in Python
2.x?
a. True c. None
b. False d. Error
91. What is the result of the expression 10 / 3 in Python 2.x?
a. 3.3333333333333335
b. 3.0
c. 3
d. 3.333
92. Which operator is used for string repetition in Python 2.x?
a. + c. /
b. * d. –
93. What is the result of the expression 5 == '5' in Python?
a. True c. None
b. False d. Error
94. What is the result of the expression 5 + '3' in Python 2.x?
a. 8
b. ‘53’
c. 35
d. Error
95. Which operator is used for float division in Python 2.x?
a. /
b. //
c. %
d. None of the above
96. What is the result of the expression 5 / 2.0 in Python 2.x?
a. 2.5 c. 2.0
b. 2 d. 2.51
97. Which of the following is a valid way to create a list of numbers
from 1 to 5 in Python 2.x?
a. [1, 2, 3, 4, 5]
b. list(1, 5)
c. range(1, 5)
d. All of the above
98. What is the result of the expression 5 != '5' in Python 2.x?
a. True c. None
b. False d. Error
99. Which operator is used for string slicing in Python 2.x?
a. : c. ..
b. :: d. ->
100. What is the result of the expression 5 / 2 in Python 3.x?
a. 2.5 c. 2.0
b. 2 d. 2.5
101. What is the result of the expression 10 / 3 in Python?
a. 3.3333333333333335
b. 3.0
c. 3
d. 3.333
102. How do you perform integer division in Python?
a. // c. %
b. / d. **
103. What is the result of the expression 5 * 2 - 3 in Python?
a. 7 c. 10
b. 8 d. Error
104. Which operator is used for concatenating two strings in Python?
a. + c. /
b. * d. –
105. What is the output of print("Hello" + " " + "World") in
Python?
a. HelloWorld c. Hello+World
b. Hello World d. Error
106. What is the result of the expression 2 ** 3 in Python?
a. 6 c. 8
b. 9 d. 5
107. What is the output of print(10 % 3) in Python?
a. 0 c. 2
b. 1 d. 3
108. How do you perform bitwise OR in Python?
a. | c. ^
b. & d. ~
109. What is the result of the expression 7 | 3 in Python?
a. 4 c. 3
b. 7 d. 0
110. What does the in operator do in Python?
a. Membership test
b. Exponentiation
c. Identity test
d. Bitwise OR
111. What is the output of print(3 in [1, 2, 3]) in Python?
a. True c. None
b. False d. Error
112. Which operator is used for checking if two values are not equal in
Python?
a. = c. !=
b. == d. <>
113. What is the result of the expression 5 != 5 in Python?
a. True c. None
b. False d. Error
114. What does the is operator do in Python?
a. Membership test
b. Exponentiation
c. Identity test
d. Bitwise OR
115. What is the output of print([] is []) in Python?
a. True c. None
b. False d. Error
116. How do you perform bitwise NOT in Python?
a. | c. ^
b. & d. ~
117. What is the result of the expression ~5 in Python?
a. -6 c. -5
b. 5 d. 6
118. What does the or operator do in Python?
a. Bitwise OR c. Bitwise AND
b. Logical OR d. Logical AND
119. What is the output of print(10 or 20) in Python?
a. 10 c. True
b. 20 d. False
120. How do you perform left shift in Python?
a. << c. &
b. >> d. |
121. What is the result of the expression 8 << 2 in Python?
a. 32 c. 64
b. 16 d. 4
122. What is the output of print("Python"[:3]) in Python?
a. Pyt c. Py
b. pyt d. Error
123. How do you perform right shift in Python?
a. >> c. &
b. << d. |
124. What is the result of the expression 16 >> 2 in Python?
a. 2 c. 8
b. 4 d. 16
125. What does the not in operator do in Python?
a. Membership test
b. Exponentiation
c. Identity test
d. Negation of membership test
126. What is the output of print(3 not in [1, 2, 3]) in
Python?
a. True c. None
b. False d. Error
127. What is the purpose of the and operator in Python?
a. Bitwise AND c. Bitwise OR
b. Logical AND d. Logical OR
128. What is the output of print(10 and 0) in Python?
a. 10 c. True
b. 0 d. False
129. What is the output of print(bool("")) in Python?
a. True c. None
b. False d. Error
130. What is the result of the expression len("Python") in Python?
a. 6 c. 5
b. 7 d. Error
131. How do you perform floor division in Python?
a. // c. %
b. / d. **
132. What is the result of the expression 7 // 2 in Python?
a. 3 c. 4
b. 3.5 d. 2
133. What is the output of print("Python".upper()) in Python?
a. python c. Python
b. PYTHON d. python
134. How do you concatenate two lists in Python?
a. list1.concat(list2)
b. list1 + list2
c. list1.extend(list2)
d. All of the above
135. What is the result of the expression list("Python") in
Python?
a. “Python”
b. [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
c. (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
d. Error
136. How do you convert a string to an integer in Python?
a. int(string) c. int.parse(string)
b. string.toInt() d. parse(int, string)
137. What is the result of the expression bool("False") in Python?
a. True c. Error
b. False d. None
138. Which is the following do you use to check if a key is present in a
dictionary?
a. key in dict
b. key.exist(dict)
c. dict.has_key(key)
d. key.exists(dict)
139. What is the output of print("hello".capitalize()) in
Python?
a. hello c. HELLO
b. Hello d. hELLO
140. How do you remove an element from a set in Python?
a. set.remove(element)
b. set.discard(element)
c. set.pop()
d. All of the above
141. What is the purpose of the sorted() function in Python?
a. Sorts a list in descending order
b. Sorts a list in ascending order
c. Sorts a dictionary by keys
d. Reverses the order of elements in a list
142. How do you find the maximum value in a list in Python?
a. max(list) c. maximum(list)
b. list.max() d. list.maximum()
143. What is the output of print("Python".lower()) in Python?
a. python c. PYTHON
b. Python d. pYTHON
144. What is the output of print(type(True)) in Python?
a. int c. bool
b. float d. str
145. How do you create an empty tuple in Python?
a. empty_tuple = []
b. empty_tuple = {}
c. empty_tuple = ()
d. empty_tuple = [None]
146. What is the output of the expression 3 * 'a' in Python?
a. ‘aaa’ c. ‘aaaa’
b. 3 d. Error
147. Which of the following is a valid way to create an empty dictionary
in Python?
a. empty_dict = {}
b. empty_dict = dict()
c. empty_dict = ()
d. empty_dict = []
148. What does the expression 3 < 5 or 2 < 4 evaluate to in
Python?
a. True
b. False
c. 2
d. Error
149. How do you check if a variable is of a specific type in Python?
a. type(var) == ‘int’
b. isinstance(var, int)
c. var.type() == int
d. typeof(var) == ‘int’
150. What is the result of the expression 5 + 2 * 3 in Python?
a. 15 c. 15
b. 11 d. Error
151. What is the output of print("Hello" * -3) in Python?
a. HelloHelloHello c. None
b. Error d. Hello
152. How do you check if a key is not present in a dictionary in Python?
a. key not in dict c. key in not dict
b. not key in dict d. key.exists(dict)
153. What is the output of print(type(True + 5)) in Python?
a. int c. bool
b. float d. str
154. What does the expression 3 + 5 * 2 evaluate to in Python?
a. 16 c. 13
b. 26 d. 18
155. How do you perform bitwise XOR in Python?
a. | c. ^
b. & d. ~
156. What is the result of the expression 7 ^ 3 in Python?
a. 4 c. 3
b. 7 d. 0
157. How do you convert a string to uppercase in Python?
a. str.uppercase()
b. string.toUpper()
c. str.upper()
d. uppercase(str)
158. What is the output of print("Python"[::-1]) in Python?
a. Python c. Error
b. nohtyP d. None
159. What does the is not operator do in Python?
a. Identity test
b. Negation of identity test
c. Membership test
d. Negation of membership test
160. What is the result of the expression 10 / 2 in Python?
a. 5.0 c. 2.5
b. 5 d. Error
161. How do you check if a variable is None in Python?
a. var is null c. var == None
b. var is None d. var.equals(None)
162. What is the output of print("Python"[-3:]) in Python?
a. Python c. thon
b. Pyth d. None
163. What does the expression not True and False evaluate to in
Python?
a. True c. Error
b. False d. None
164. How do you convert a number to a string in Python?
a. str(number)
b. number.toString()
c. string(number)
d. format(number)
165. What is the output of print(10.5 // 2) in Python?
a. 5.0 c. 5.5
b. 5 d. Error
166. What is the result of the expression int("10") +
float("5.5") in Python?
a. 15.5 c. 10
b. 15 d. Error
167. How do you check if a string is numeric in Python?
a. string.isnumeric()
b. str.isnumeric()
c. isnumeric(string)
d. isnumeric(str)
168. What is the output of print(7 & 3) in Python?
a. 4 c. 3
b. 7 d. 0
169. What is the result of the expression round(3.567, 2) in
Python?
a. 3.6 c. 3.57
b. 3.56 d. 4.0
170. In the Python statement x = a + 5 – b:
a and b are ________
a + 5 - b is ________
a. terms, a group
b. operators, a statement
c. operands, an expression
d. operands, an equation
171. Which is the correct operator for power(xy)?
a. X^y
b. X**y
c. X^^y
d. None of the mentioned
172. What is the output of the following addition (+) operator:
a = [10, 20]
b = a
b += [30, 40]
print(a)
print(b)
a. [10, 20, 30, 40]
[10, 20, 30, 40]
b. [10, 20]
[10, 20, 30, 40]
c. [10, 20, 10, 20]
[10, 20, 30, 40]
d. [10, 20]
[30, 40]
173. Which function overloads the >> operator?
a. more()
b. gt()
c. ge()
d. None of the above
174. What is the value of the expression 100 / 25?
a. 4 c. 0
b. 4.0 d. 25
175. Which one of these is floor division?
a. //
b. /
c. %
d. None of the above
176. What is the output of the following assignment operator:
a = 10
b = a -= 2
print(b)
a. 8
b. 10
c. Syntax Error
d. No error but no output too
177. Which operator is overloaded by the or() function?
a. || c. //
b. | d. /
178. Should you use the == operator to determine whether objects of
type float are equal?
a. Yes b. No
179. What is the output of the following code:
x = 6
y = 2
print(x ** y)
print(x // y)
a. 66
0
b. 36
0
c. 66
3
d. 36
3
180. What is the output of the following program:
i = 0
while i < 3:
print i
i++
print i+1
a. 0 2 1 3 2 4 c. Error
b. 0 1 2 3 4 5 d. 1 0 2 4 3 5
181. Suppose the following statements are executed:
a = 100
b = 200
What is the value of the expression a and b?
a. True d. 200
b. 0 e. 100
c. False
182. Operators with the same precedence are evaluated in which
manner?
a. Left to Right
b. Right to Left
c. Can’t say
d. None of the mentioned
183. Which of the following operators has the highest precedence?
a. not c. *
b. & d. +
184. Given a function that does not return any value, what value is
shown when executed at the shell?
a. int c. void
b. bool d. None
185. The function sqrt() from the math module computes the square
root of a number. Will the highlighted line of code raise an
exception?
x = -100
from math import sqrt
x > 0 and sqrt(x)
a. Yes c. void
b. No d. None
186. Which one of the following has the same precedence level?
a. Addition and subtraction
b. Multiplication, division and addition
c. Multiplication, division, addition and subtraction
d. Addition and multiplication
187. What is the output of the following code:
print(bool(0), bool(3.14159), bool(-3),
bool(1.0+1j))
a. True True False True
b. False True True True
c. True True False True
d. False True False True
188. What is the output of the expression print(-18 // 4)
a. -4 c. 4
b. -5 d. 5
189. 4 is 100 in binary and 11 is 1011. What is the output of the
following bitwise operators?
a = 4
b = 11
print(a | b)
print(a >> 2)
a. 15
1
b. 14
1
190. What is the value of the following Python Expression:
print(36 / 4)
a. 9.0 b. 9
191. What is the output of the following code:
x = 100
y = 50
print(x and y)
a. True
b. 100
c. False
d. 50
192. What is the output of print(2 * 3 ** 3 * 4)?
a. 216 b. 864
193. What is the output of print(2 ** 3 ** 2)?
a. 64 b. 512
194. What is the output of the following code:
x = 6
y = 2
print(x ** y)
print(x // y)
a. 66 c. 66
0 3
b. 36 d. 36
0 3
195. What is the output of the following assignment operator:
y = 10
x = y += 2
print(x)
a. 12 c. SyntxError
b. 10
196. Which of the following operators has the highest precedence?
a. not c. *
b. & d. +
197. What is the output of the following Python code:
x = 10
y = 50
if x ** 2 > 100 and y < 100:
print(x, y)
a. 100 500 c. None
b. 10 50
198. What is the output of the following addition (+) operator:
a = [10, 20]
b = a
b += [30, 40]
print(a)
print(b)
a. [10, 20, 30, 40] b. [10, 20]
[10, 20, 30, 40] [10, 20, 30, 40]
199. Bitwise shift operators (<<, >>) has higher precedence than
Bitwise And(&) operator.
a. False b. True
200. What is the output of print(10 - 4 * 2)?
a. 2 b. 12
201. What is the output of the expression print(-18 // 4)?
a. -4 c. -5
b. 4 d. 5
202. What is the output of print(2%6)?
a. ValueError
b. 0.33
c. 2
203. What is the output of the following code:
print(bool(0), bool(3.14159), bool(-3),
bool(1.0+1j))
a. True True False True
b. False True True True
c. True True False True
d. False True False True
204. Which one of the following is correct way of declaring and
initialising a variable, x with value 5?
a. int x
x=5
b. int x=5
c. x=5
d. declare x=5
205. Which of the following is not valid variable name in Python?
a. _var c. var11
b. var_name d. 11var
206. Which one is false regarding local variables?
a. These can be accessed only inside owning function
b. Any changes made to local variables does not reflect outside the
function.
c. These remain in memory till the program ends
d. None of the above
207. Which one is false regarding global variables?
a. Global variables can only be read inside the function declaring
the variable as global inside the function.
b. Global variables remain in memory till the end of the program
c. Global variables are those which are declared in global scope.
d. None of the above
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
209. What will be the output of the following Python code:
def fn():
global var1
var1=10
var1=var1*5
print(var1)
var1=5
fn()
print(var1)
a. 25
5
b. 50
5
c. 25
25
d. 50
50
210. What will be the output of the following Python code:
x=5
def function1():
global x
y=x+x*2
print(y)
x=7
function1()
print(x)
a. 21
7
b. 15
5
c. 21
5
d. 15
7
211. What will be the value of variable y after execution of following
Python code:
x="55"
y=x + str(9)
a. 64 c. 559
b. 9 d. Error
212. Which of the following is incorrect regarding variables in Python?
a. Variable names in Python cannot start with a number. However,
it can contain a number in any other position of variable name
b. Variable names can start with an underscore
c. Data type of variable names should not be declared
d. None of the above
213. Which of the following will give error?
a. a=b=c=1
b. a,b,c=1
c. a,b,c=1, python, 1.5
d. None of the above
214. How many keywords are there in python 3.7?
a. 32 c. 31
b. 33 d. 30
215. What is the maximum length of an identifier in Python?
a. 32 c. 63
b. 31 d. None of the above
216. All keywords in Python are in:
a. Lowercase
b. Uppercase
c. Both uppercase and lowercase
d. None of the above
217. Which of the following statement is false?
a. Variable names can be arbitrarily long.
b. They can contain both letters and numbers.
c. Variable name can begin with underscore.
d. Variable name can begin with number.
218. Which of the following is a valid variable?
a. var@ c. Class
b. 32var d. abc_a_c
219. Why are local variable names beginning with an underscore
discouraged?
a. They confuse the interpreter
b. They are used to indicate a private variables of a class
c. They are used to indicate global variables
d. They slow down execution
220. Which of these are keyword?
a. In c. Assert
b. Is d. All of the above
221. What is the output of the following code : print 5//2
a. 2 c. 2.0
b. 2.5 d. Error
222. Arrange the following in order of precedence:
1. Exponentiation
2. Parentheses
3. Multiplication and division
4. Addition and subtraction
a. 1,2,3,4 c. 1,2,4,3
b. 2,1,3,4 d. 2,3,1,4
223. Which of this statement will give an error?
a. a++ c. a+=1
b. ++a d. Both A and B
224. Which operator is used to calculate power of x raised to y.
a. x^y c. x**y
b. x*y d. None of the above
225. Operators with the same precedence are evaluated from
__________.
a. Left to right
b. Right to left
c. Depends on compiler
d. None of the above
226. “in” is an operator in Python.
a. True
b. False
c. Neither true nor false
d. None of the above
227. What will be the output of statment 2**2**2**2
a. 16
b. 256
c. 32768
d. 65536
228. What will be the output of the following code:
a = 1
b = ++a
print(b is a)
a. True c. Error
b. False d. None of the above
229. Who developed Python Programming Language?
a. Wick van Rossum
b. Rasmus Lerdorf
c. Guido van Rossum
d. Niene Stom
230. Which type of Programming does Python support?
a. object-oriented programming
b. structured programming
c. functional programming
d. all of the mentioned
231. Is Python case sensitive when dealing with identifiers?
a. No
b. Yes
c. machine dependent
d. none of the mentioned
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
234. All keywords in Python are in _________
a. Capitalized
b. lower case
c. UPPER CASE
d. None of the mentioned
235. What will be the value of the following Python expression?
4 + 3 % 5
a. 7 c. 4
b. 2 d. 1
236. Which of the following is used to define a block of code in Python
language?
a. Indentation
b. Key
c. Brackets
d. All of the mentioned
237. Which keyword is used for function in Python language?
a. Function c. Fun
b. Def d. Define
238. What will be the output of the following Python code:
i = 1
while True:
if i%3 == 0:
break
print(i)
i + = 1
a. 1 2 3
b. Error
c. 1 2
d. None of the mentioned
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
242. What are the values of the following Python expressions?
2**(3**2)
(2**3)**2
2**3**2
a. 512, 64, 512 c. 512, 512, 64
b. 512, 512, 512 d. 64, 64, 64
243. What will be the output of the following Python code:
l=[1, 0, 2, 0, 'hello', '', []]
list(filter(bool, l))
a. [1, 0, 2, ‘hello’, ”, []]
b. Error
c. [1, 2, ‘hello’]
d. [1, 0, 2, 0, ‘hello’, ”, []]
244. Which of the following functions is a built-in function in Python?
a. factorial() c. seed()
b. print() d. sqrt()
245. The following python program can work with ____ parameters.
def f(x):
def f1(*args, **kwargs):
print("Sanfoundry")
return x(*args, **kwargs)
return f1
a. any number of
b. 0
c. 1
d. 2
246. What will be the output of the following Python function:
min(max(False,-3,-4), 2,7)
a. -4 c. 2
b. -3 d. False
247. Which of the following is not a core data type in Python
programming?
a. Tuples c. Class
b. Lists d. Dictionary
248. What will be the output of the following Python expression if
x=56.236?
print("%.2f"%x)
a. 56.236 c. 56.0000
b. 56.23 d. 56.24
249. Which of the following is the definition for packages in Python?
a. A set of main modules
b. A folder of python modules
c. Several files containing Python definitions and statements
d. A set of programs making use of Python modules
250. What will be the output of the following Python code:
class tester:
def __init__(self, id):
self.id = str(id)
id="224"
>>>temp = tester(12)
>>>print(temp.id)
a. 12 c. None
b. 224 d. Error
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 a 51 a 101 a 151 c 201 c
2 b 52 b 102 a 152 a 202 c
3 a 53 b 103 a 153 a 203 c
4 a 54 a 104 a 154 c 204 b
5 c 55 b 105 b 155 c 205 d
6 b 56 c 106 c 156 a 206 c
7 b 57 a 107 b 157 c 207 a
8 b 58 c 108 a 158 b 208 c
9 b 59 b 109 b 159 b 209 b
10 a 60 b 110 a 160 a 210 d
11 c 61 c 111 a 161 b 211 c
12 a 62 b 112 c 162 c 212 a
13 b 63 b 113 b 163 b 213 c
14 a 64 a 114 c 164 a 214 b
15 a 65 a 115 b 165 b 215 d
16 a 66 a 116 d 166 b 216 a
17 c 67 a 117 a 167 a 217 d
18 c 68 d 118 b 168 c 218 d
19 a 69 b 119 a 169 c 219 b
20 b 70 a 120 a 170 c 220 d
21 b 71 a 121 b 171 b 221 a
22 b 72 a 122 a 172 a 222 c
23 a 73 a 123 a 173 d 223 d
24 b 74 a 124 b 174 a 224 c
25 b 75 a 125 d 175 a 225 a
26 c 76 a 126 b 176 c 226 a
27 c 77 a 127 b 177 d 227 d
28 b 78 a 128 b 178 a 228 b
29 a 79 a 129 b 179 d 229 c
30 c 80 b 130 a 180 c 230 d
31 a 81 b 131 a 181 d 231 b
32 c 82 b 132 a 182 a 232 c
33 d 83 b 133 b 183 c 233 a
34 b 84 a 134 b 184 d 234 d
35 d 85 c 135 b 185 a 235 a
36 b 86 c 136 a 186 a&c 236 a
37 a 87 b 137 a 187 b 237 b
38 b 88 b 138 a 188 a 238 b
39 c 89 a 139 b 189 a 239 d
40 c 90 b 140 a 190 a 240 c
41 c 91 c 141 b 191 d 241 c
42 b 92 b 142 a 192 c 242 a
43 a 93 b 143 a 193 b 243 c
44 a 94 d 144 c 194 d 244 b
45 b 95 b 145 c 195 a 245 a
46 c 96 a 146 a 196 c 246 d
47 a 97 c 147 a&b 197 c 247 c
48 b 98 b 148 a 198 a 248 d
49 b 99 a 149 b 199 b 249 b
50 a 100 d 150 b 200 c 250 a
CHAPTER 4
Control Flow Statements
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.
Multiple choice questions
1. Which of the following is not used as loop in Python?
a. for loop c. do-while loop
b. while loop d. None of the above
2. Which of the following is False regarding loops in Python?
a. Loops are used to perform certain tasks repeatedly.
b. While loop is used when multiple statements are to executed
repeatedly until the given condition becomes False.
c. While loop is used when multiple statements are to be executed
repeatedly until the given condition becomes True.
d. for loop can be used to iterate through the elements of lists.
3. Which of the following is True regarding loops in Python?
a. Loops should be ended with keyword “end”.
b. No loop can be used to iterate through the elements of strings.
c. Keyword “break” can be used to bring control out of the current
loop.
d. Keyword “continue” is used to continue with the remaining
statements inside the loop.
4. What will be the output of given Python code?
n=7
c=0
while(n):
if(n>5):
c=c+n-1
n=n-1
else:
break
print(n)
print
a. 5 11 c. 7 11
b. 5 9 d. 5 2
5. What will be the output of given Python code?
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print
a. 2 c. 4
b. 0 d. 3
6. Which of the following Python code will give different output from
the others?
a. for i in range(0,5):
print(i)
b. for j in [0,1,2,3,4]:
print(j)
c. for k in [0,1,2,3,4,5]:
print(k)
d. for l in range(0,5,1):
print(l)
7. How many times will the loop run?
i=2
while(i>0):
i=i-1
a. 2 c. 1
b. 3 d. 0
8. What will be the output of the following Python code?
list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]
sum = 0
sum1 = 0
forelem in list1:
if (elem % 2 == 0):
sum = sum + elem
continue
if (elem % 3 == 0):
sum1 = sum1 + elem
print(sum , end=" ")
print(sum1)
a. 8 9 c. 2 3
b. 8 3 d. 8 12
9. What will be the output of the following Python code:
str1="learn python"
str2=""
str3=""
for x in str1:
if(x=="r" or x=="n" or x=="p"):
str2+=x
pass
if(x=="r" or x=="e" or x=="a"):
str3+=x
print(str2,end=" ")
print(str3)
a. rnpnea c. rnpea
b. rnpn ear d. rnp ear
10. What will be the output of the following Python code:
for i in range(0,2,-1):
print("Hello")
a. Hello c. No Output
b. Hello Hello d. Error
11. Which one of the following is a valid Python if statement :
a. if a>=2 : c. if (a => 22)
b. if (a >= 2) d. if a >= 22
12. What keyword would you use to add an alternative condition to an
if statement?
a. else if c. elif
b. elseif d. None of the above
13. Can we write if/else into one line in Python?
a. Yes
b. No
c. if/else not used in python
d. None of the above
14. In a Python program, a control structure:
a. Defines program-specific data structures
b. Directs the order of execution of the statements in the program
c. Dictates what happens before the program starts and after it
terminates
d. None of the above
15. What will be output of this expression:
'p' + 'q' if '12'.isdigit() else 'r' + 's'
a. pq c. pqrs
b. rs d. pq12
16. Which statement will check if a is equal to b?
a. if a = b: c. if a === c:
b. if a == b: d. if a == b
17. Does python have switch case statement?
a. True
b. False
c. Python has switch statement but we cannot use it
d. None of the above
18. Which of the following is a valid for loop in Python?
a. for(i=0; i< n; i++)
b. for i in range(0,5):
c. for i in range(0,5)
d. for i in range(5)
19. Which of the following sequences would be generated bt the given
line of code?
range (5, 0, -2)
a. 5 4 3 2 1 0 -1 c. 5 3 1
b. 5 4 3 2 1 0 d. None of the above
20. A while loop in Python is used for what type of iteration?
a. indefinite c. definite
b. discriminant d. indeterminate
21. When does the else statement written after loop executes?
a. When break statement is executed in the loop
b. When loop condition becomes false
c. Else statement is always executed
d. None of the above
22. What will be the output of the following code:
x = "abcdef"
i = "i"
whilei in x:
print(i, end=" ")
a. a b c d e f c. iiiii.....
b. abcdef d. No Output
23. What will be the output of the following code:
x = "abcd"
fori in range(len(x)):
print(i)
a. abcd c. 1 2 3 4
b. 0 1 2 3 d. a b c d
24. What will be the output of the following code:
x = 12
fori in x:
print(i)
a. 12 c. Error
b. 1 2 d. None of the above
25. A loop becomes infinite loop if a condition never becomes
________.
a. TRUE c. Null
b. FALSE d. Both A and C
26. If the else statement is used with a while loop, the else statement is
executed when the condition becomes _______.
a. TRUE c. Infinite
b. FALSE d. Null
27. Python programming language allows to use one loop inside
another loop known as?
a. switch c. nested
b. foreach d. forall
28. The ________ statement is a null operation.
a. break c. return
b. exit d. pass
29. The continue statement can be used in:
a. while loop c. do-while
b. for loop d. Both A and B
30. Which of the following will invert the result of relational
expression?
a. AND
b. OR
c. NOT
d. XOR
31. Which operator return TRUE, if both conditions are TRUE?
a. AND c. NOT
b. OR d. XOR
32. Which operator is used with multiple conditions in if statement?
a. Assignment c. Arithmetic
b. Logical d. Unary
33. How many conditions can be used with single if statement?
a. One c. Four
b. Two d. Multiple
34. In Python programming if statements are written after ________
tabs.
a. One c. Three
b. Two d. Four
35. Statement or set of statements are executed only if provided
relational expression is.
a. TRUE c. NEUTRAL
b. FALSE d. EQUAL
36. In Python which of the following operator is used after condition
of if statement?
a. Semicolon (;) c. Colon (:)
b. Comma (,) d. Dot (.)
37. In Python which of the following keyword is used to implement
selection structure?
a. if c. sel
b. condition d. select
38. Can we write if/else into one line in Python?
a. Yes
b. No
c. if/else not used in python
d. None of the above
39. Which one of the following is a valid Python if statement:
a. if a>=2 :
b. if (a >= 2)
c. if (a => 22)
d. if a >= 22s
40. What keyword would you use to add an alternative condition to an
if statement?
a. else if c. elif
b. elseif d. None of the above
41. What is the output of the given below program:
if1+3==7:
print("Hello")
else:
print("Know Program")
a. Hello
b. Know Program
c. Compiled Successfully, No Output.
d. Error
42. What is the output of the given below program:
if 3+4==7:
print("Hi")
else:
print("Know Program")
print("Hello")
a. Hi
Know Program
b. Hi
Hello
c. Know Program
Hello
d. Error
43. Find the output of the given Python program:
a =25
if a <15:
print("Hi")
if a <=30:
print("Hello")
else:
print("Know Program")
a. Hi
b. Hello
c. Know Program
d. Compiled Successfully, No Output.
44. What is the output of the given program?
a =25
if a >15:
print("Hi")
if a <=30:
print("Hello")
else:
print("Know Program")
a. Hi
b. Hello
c. Hi
Hello
d. Hello
Know Program
45. Find the output of the given Python program:
a, b, c =1,3,5
if a >0:
if b <2:
print("Hi")
elif c >3:
print("Hello")
else:
print("Know Program")
a. Hi
b. Hello
c. Know Program
d. Compiled Successfully, No Output.
46. Find the output of the given Python program:
a, b, c =1,3,5
if a + b + c:
print("Hello")
else:
print("Know Program")
a. Hello
b. Know Program
c. Compiled Successfully, No Output.
d. Error
47. What is the output of the given program:
if a < b:
print("Hello")
else:
print("Know Program")
a. Hello
b. Know Program
c. Compiled Successfully, No Output.
d. Error
48. What is the output of the given below program:
a = b =true
if(a and b):
print("Hello")
else:
print("Know Program")
a. Hello
b. Know Program
c. Compiled Successfully, No Output.
d. Error
49. Which of following is not a decision-making statement?
a. if-elif statement
b. for statement
c. if -else statement
d. if statement
50. What will be the output of the following Python code:
list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]
sum = 0
sum1 = 0
forelem in list1:
if (elem % 2 == 0):
sum = sum + elem
continue
if (elem % 3 == 0):
sum1 = sum1 + elem
print(sum , end=" ")
print(sum1)
a. 8 9 c. 2 3
b. 8 3 d. 8 12
51. What will be the output of the following Python code:
If 4+5==10:
print("TRUE")
else:
print("false")
print ("True")
a. False
True
b. True
c. True
d. false none
52. What keyword would you use to add an alternative condition to an
if statement?
a. else if c. elif
b. elseif d. None of the above
53. What will be the output of the following Python code:
str1="learn python"
str2=""
str3=""
for x in str1:
if(x=="r" or x=="n" or x=="p"):
str2+=x
pass
if(x=="r" or x=="e" or x=="a"):
str3+=x
print(str2,end=" ")
print(str3)
a. rnpnea c. rnpea
b. rnpn ear d. rnp ear
54. Predict the output of the following code:
X=3
If x>2 or x<5 and x==6:
Print("ok")
else:
print("no output")
a. ok c. no output
b. okok d. none of above
55. Predict the output of the following code:
x,y=2,4
if(x+y= =10):
print("true")
else:
print("false")
a. true c. no output
b. false d. None
56. Consider the following code segment:
a = int(input("Enter an integer: "))
b = int(input("Enter an integer: "))
if a <= 0:
b = b +1
else:
a = a + 1
if a > 0 and b > 0:
print ("W")
elif a > 0:
print("X")
if b > 0:
print("Y")
else:
print("Z")
What letters will be printed if the user enters
-1 for a and -1 for b?
a. Only W c. Only Y
b. Only X d. Only Z
57. If the user inputs : 2<ENTER>, what does the following code
snippet print?
x = float(input())
if(x==1):
print("Yes")
elif (x >= 2):
print("Maybe")
else:
print ("No")
a. Yes c. Maybe
b. No d. Nothing is printed
58. What will be the output of given Python code:
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print
a. 2 c. 4
b. 0 d. 3
59. What does the following Python program display ?
x = 3
if x == 0:
print ("Am I here?", end = ' ')
elif x == 3:
print("Or here?", end = ' ')
else :
pass
print ("Or over here?")
a. Am I here?
b. Or here?
c. Am I here? Or here?
d. Or here ?
60. Which one of the following if statements will not execute
successfully?
1. if (1, 2) ;
print(‘foo’)
2. if (1, 2) :
print(‘foo’)
3. if (1) :
print( ‘foo’ )
4. if (1) ;
print( ‘foo’ )
a. 1 ,4 c. 2,4
b. 2 d. 4
61. What will be the output of below program:
a=1
if( a):
print("a is non zero")
else:
print("its results is True")
a. false c. Its result is True
b. True d. a is nonzero
62. The ……………… statement forms the selection construct in
Python.
a. If else if c. For ;
b. .if d. for
63. In Python, …………………. defines a block of statements.
a. Block c. indentation
b. loop d. {}
64. An ………… statement has less number of conditional checks than
two successive ifs.
a. If else if c. if-else
b. if elif d. none
65. The……….. clause can occur with an if as well as with loops.
a. else c. continue
b. break d. none
66. The ………….statement terminates the execution of the whole
loop.
a. continue c. breake
b. exit d. break
67. The ……….. operator tests if a given value is contained in a
sequence or not.
a. In: c. not in
b. in d. none
68. An empty /null statement in Python is ……………. .
a. pass c. null
b. none d. none
69. The break and continue statements, together are called
…………….statement.
a. Jump c. compound
b. goto d. none
70. The order of statement execution in the form of top to bottom is
known as………...
a. alternate c. flow of data
b. sequence d. flow chart
71. The two membership operators are ……….and …………
a. in, not in c. =,==
b. true , false d. none
72. A graphical representation of an algorithm to solve a problem is
called ……………
a. flow of data d. none
b. barchart e. Show Answer
c. flow chart
73. What is the logical expression for the following:
Either A is greater than B or A is less than C
a. A>B or A<C c. A>Band C
b. A>B and A<C d. A>B or C
74. What is the logical expression for the following:
Name is rohit and age between 18 and 35
a. name==rohit and age >=18 and age<=35
b. name==rohit and age >=18 or age<=35
c. name==rohit or age >=18 and age<=35
d. none
75. What is the logical expression for the following:
Donation in the range of4000-5000 or guest=1
a. (donation>=4000 and donation<=5000) or guest==1
b. donation>=4000 or donation<=5000 or guest==1
c. donation>=4000 and (donation<=5000 or guest==1)
d. donation>=4000 and donation<=5000) or guest==1
76. State which of the following statement are true .
1. If,elif ,else are not compound statement.
2. Else if can be used in python.
3. Indentation while working with blocks is not necessary in
python.
4. A pass statement is a null operation;it does nothing.
a. 1
b. 2 ,3
c. 3
d. 4
77. In a Python program, a control structure:
a. Defines program-specific data structures
b. Directs the order of execution of the statements in the program
c. Dictates what happens before the program starts and after it
terminates
d. None of the above
78. Does Python have a switch case statement?
a. True
b. False
c. Python has switch statement but we can not use it.
d. None of the above
79. What will be output of this expression:
'p' + 'q' if '12'.isdigit() else 'r' + 's'
a. pq c. pqrs
b. rs d. pq12
80. Which statement will check if a is equal to b?
a. if a == b: c. if a === c:
b. if a = b: d. if a == b
81. Checking multiple conditions in Python requires………..
statement
a. if c. switch
b. if……. elif d. None of these
82. if the condition is …………. , the statements of if block will be
executed otherwise the statements in the ……….. block will be
executed
a. false, true
b. true, else
c. both options are true
d. Can’t say
83. What will be output after execution of the following code:
a=11
B=5
If(a//b==2):
Print ("Yes")
else :
Print("No")
a. 2.5 c. No
b. Yes d. 21
84. What will be output after execution of the following code:
a=11
b=5
if (a%b==0):
print ( "Greater")
if (a//b==0):
print ( "Example")
else:
print ("Sooo Sorry")
a. Sooo Sorry c. Example
b. Great d. Great Example
85. What will be the output of the following program if we input 8:
Ch= int ("Enter Day of week (1 to 7 "))
If ch==1:
print ("Monday")
elifch==2:
print ("Tuesday")
elifch==3:
print ("Wednesday")
elifch==4:
Page 38 of 55
print ("Thursday")
elifch==5:
print ("Friday")
elifch==6:
print ("Saturday")
else:
print ("Sunday")
a. Sunday
b. Monday
c. All days will be printed
d. No Output
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
88. Which of the following is NOT a control flow statement in Python?
a. If statement c. Elif statement
b. Else statement d. While loop
89. The following code snippet will print what:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
a. x is greater than 5
b. x is not greater than 5
c. Nothing
90. The following code snippet will print what:
for i in range(10):
print(i)
a. 0 to 9 c. 2 to 11
b. 1 to 10 d. None of the above
91. Which of the following is a valid break statement:
a. break
b. break 1
c. break “while loop”
d. break()
92. The following code snippet will print what:
while True:
print("Hello, world!")
break
a. Hello, world!
b. Hello, world!
c. Hello, world! ...
d. Infinite loop
93. Which of the following is a valid nested loop:
a. for i in range(10):
for j in range(10):
print(i, j)
b. for i in range(10):
if i % 2 == 0:
for j in range(10):
print(i, j)
c. for i in range(10):
for j in range(10):
if i % 2 == 0:
print(i, j)
d. All of the above
94. Which of the following is a valid pass statement:
a. pass c. pass “function”
b. pass 1 d. None of the above
95. The following code snippet will print what:
defmy_function():
pass
print(my_function())
a. None c. “my_function”
b. “None” d. None of the above
96. Which of the following is NOT a valid control flow statement in
Python?
a. If statement
b. Else statement
c. Elif statement
d. For loop
e. While loop
f. Switch statement
97. The following code snippet will print what:
while True:
if x > 5:
continue
print("x is not greater than 5")
a. x is not greater than 5
b. x is not greater than 5 x is not greater than 5 ...
c. Infinite loop
d. Error
98. Which of the following is a valid nested if-elif statement?
a. (A)
if x > 5:
if y > 10:
print(“x is greater than 5 and y is greater than 10”)
b. Python
if x > 5:
if y > 10:
print(“x is greater than 5 and y is greater than 10”)
else:
print(“x is greater than 5 but y is not greater than 10”)
c. if x > 5:
if y > 10:
print(“x is greater than 5 and y is greater than 10”)
elif y > 5:
print(“x is greater than 5 but y is not greater than 10 but y is
greater than 5”)
else:
print(“x is greater than 5 but y is not greater than 10 and y is not
greater than 5”)
d. All of the above
99. Which of the following is NOT a valid control flow statement in
Python, onwards from 96?
a. If statement
b. Else statement
c. Elif statement
d. For loop
e. While loop
f. Generator expression.
100. The following code snippet will print what:
Python
my_list = [1, 2, 3, 4, 5]
print(list(filter(lambda x: x % 2 == 0,
my_list)))
a. [1, 3, 5] c. [1, 2, 3, 4, 5]
b. [2, 4] d. None of the above
101. 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()
102. 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()
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):
105. Which of the following is NOT a valid way to sort a list?
a. my_list.sort()
b. my_list.sort(reverse=True)
c. my_list.sort(key=lambda x: x[1])
d. sorted(my_list)
106. Which of the following is NOT a valid way to reverse a list?
a. my_list.reverse()
b. my_list = my_list[::-1]
c. my_list = sorted(my_list, reverse=True)
d. None of the above
107. Which of the following is NOT a valid way to check if a value is in
a list?
a. my_list.count(value) > 0
b. value in my_list
c. my_list.index(value) >= 0
d. None of the above
108. Which of the following is NOT a valid way to append a value to a
list?
a. my_list.append(value)
b. my_list += [value]
c. my_list.insert(len(my_list), value)
d. None of the above
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
111. Which of the following is NOT a valid way to check if a list is
empty?
a. notmy_list
b. len(my_list) == 0
c. my_list is None
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
114. Which of the following is NOT a valid way to create a list
comprehension?
a. [value for value in my_list]
b. [value for value in my_list if value > 5]
c. [value * 2 for value in my_list]
d. [value[0] for value in my_list]
115. Which of the following is NOT a valid way to iterate over a
dictionary?
a. for key in my_dict:
b. for value in my_dict.values():
c. for key, value in my_dict.items():
d. for item in my_dict.items();
116. Which of the following is NOT a valid way to check if a key is in a
dictionary?
a. key in my_dict
b. my_dict.has_key(key)
c. my_dict.get(key) is not None
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
119. Which of the following is NOT a valid way to create a dictionary
comprehension?
a. {key: value for key, value in my_dict.items()}
b. {key for key in my_dict.keys()}
c. {value for value in my_dict.values()}
d. {key * 2: value for key, value in my_dict.items()}
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
124. Which of the following is NOT a valid way to check if a value is in
a list?
a. my_list.count(value) > 0
b. value in my_list
c. my_list.index(value) >= 0
d. None of the above
125. Which of the following is NOT a valid way to append a value to a
list?
a. my_list.append(value)
b. my_list += [value]
c. my_list.insert(len(my_list), value)
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
128. Which of the following is NOT a valid way to check if a list is
empty?
a. notmy_list
b. len(my_list) == 0
c. my_list is None
129. Which of the following is a conditional statement?
a. I went to the store.
b. If I have money, I will buy milk.
c. The sky is blue.
d. I like to eat ice cream.
130. What is the syntax for an if statement in Python?
a. if condition:
code_block
b. if condition:
c. if condition then:
code_block
d. if condition then
code_block
131. What is the output of the following code:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
a. x is greater than 5
b. x is not greater than 5
c. None
d. Error
132. Which of the following is an example of a nested if statement:
a. if condition1:
if condition2:
code_block
b. if condition1 and condition2:
code_block
c. if condition1 or condition2:
code_block
d. All of the above
133. What is the output of the following code:
x = 10
y = 5
if x > y:
if y > 0:
print("x is greater than y and y is greater
than 0")
else:
print("x is greater than y but y is not greater
than 0")
else:
print("x is not greater than y")
a. x is greater than y and y is greater than 0
b. x is greater than y but y is not greater than 0
c. x is not greater than y
d. Error
134. What is the output of the following code:
x = 10
y = 5
if x > y:
print("x is greater than y")
else:
if x < y:
print("x is less than y")
else:
print("x is equal to y")
if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")
if x == y:
print("x is equal to y")
else:
print("x is not equal to y")
a. x is greater than y
b. x is less than y
c. x is equal to y
d. None of the above
135. Which of the following is a valid use of the elif statement?
a. if condition1: elif condition2:
b. if condition1: elif condition2:
c. if condition1: else if condition2:
d. All of the above
136. Which of the following is a valid use of the else statement?
a. if condition1: elif condition2: else:
b. if condition1: else:
c. if condition1: else if condition2:
d. All of the above
137. Which of the following is a nested conditional statement?
a. if condition1: if condition2:
b. if condition1 or condition2:
c. if condition1: else if condition2:
d. None of the above
138. Which of the following is a valid use of the and operator?
a. if condition1 and condition2:
b. if condition1 or condition2:
c. if condition1: else if condition2:
d. None of the above
139. Which of the following is a valid use of the or operator?
a. if condition1 and condition2:
b. if condition1 or condition2:
c. if condition1: else if condition2:
d. None of the above
140. Which of the following is a valid use of the not operator?
a. if not condition:
b. if condition or not condition:
c. if condition: else if not condition:
d. All of the above
141. What is the output of the following code:
x = 10
y = 5
if x > y:
print("x is greater than y")
else:
if x < y:
print("x is less than y")
else:
print("x is equal to y")
if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")
if x == y:
print("x is equal to y")
else:
print("x is not equal to y")
if not x > y:
print("x is not greater than y")
else:
print("x is greater than y")
a. x is greater than y
b. x is less than y
c. x is equal to y
d. None of the above
142. Which of the following is a valid use of the in operator:
a. if value in list:
b. if value not in list:
c. if value is in list:
d. All of the above
143. Which of the following is a valid use of the is operator:
a. if value is None:
b. if value is not None:
c. if value is True:
d. All 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
145. What is the output of the following code:
x = 10
y = 5
x = x if x > y else y
print(x)
a. 10 c. None
b. 5 d. Error
146. What is the output of the following code:
x = 10
y = 5
x = x if x> y else "y is greater than x"
print(x)
a. 10
b. y is greater than x
c. None
d. Error
147. Which of the following is a valid use of the lambda expression:
a. lambda x: x + 1
b. lambda x, y: x + y
c. lambda: x + 1
d. All of the above
148. What is the output of the following code:
x = 10
y = 5
def add(x, y):
return x + y
add_lambda = lambda x, y: x + y
print(add(x, y))
print(add_lambda(x, y))
a. 15
b. 10
c. None
d. Error
149. Which of the following is a valid use of the map() function:
a. map(function, iterable)
b. map(iterable, function)
c. map(function, function, iterable)
d. None of the above
150. What is the output of the following code:
x = [1, 2, 3, 4, 5]
defadd_one(x):
return x + 1
y = map(add_one, x)
print(list(y))
a. [1, 2, 3, 4, 5] c. None
b. [2, 3, 4, 5, 6] d. Error
151. Which of the following is a valid use of the filter() function?
a. filter(function, iterable)
b. filter(iterable, function)
c. filter(function, function, iterable)
d. None of the above
152. What is the output of the following code:
x = [1, 2, 3, 4, 5]
defis_even(x):
return x % 2 == 0
y = filter(is_even, x)
print(list(y))
a. [1, 2, 3, 4, 5] c. None
b. [2, 4] d. Error
153. Which of the following is a valid use of the reduce() function?
a. reduce(function, iterable)
b. reduce(iterable, function)
c. reduce(function, function, iterable)
d. None of the above
154. Which of the following is a valid use of the break statement?
a. break
b. break out of loop
c. break loop
d. All of the above
155. Which of the following is a valid use of the continue statement?
a. continue
b. continue loop
c. skip loop
d. All of the above
156. What is the output of the following code:
fori in range(10):
ifi == 5:
break
print(i)
a. 0 1 2 3 4
b. 0 1 2 3 4 5
c. 0 1 2 3 4 5 6 7 8 9
d. None
157. What is the output of the following code:
fori in range(10):
ifi == 5:
continue
print(i)
a. 0 1 2 3 4
b. 0 1 2 3 4 5
c. 0 1 2 3 4 5 6 7 8 9
d. None
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
160. Is the below syntax true for the while condition:
while condition:
code
a. Yes b. No
161. What is the output of the following code:
i = 0
whilei< 10:
print(i)
i += 1
a. 0 1 2 3 4 5 6 7 8 9
b. None
162. Which of the following is a valid use of the do-while loop?
do {
code
} while condition;
a. Yes b. NO
163. What is the output of the following code:
i = 0
do:
print(i)
i += 1
whilei< 10
a. 0 1 2 3 4 5 6 7 8 9
b. None
164. Which of the following is the correct syntax for an if statement:
a. if (condition) { statement; }
b. if (condition) { statement; } else { statement; }
c. if (condition) { statement1; } elseif (condition) { statement2; }
else { statement3; }
d. All of the above
165. What is the output of the following code:
int a = 10;
if (a > 5) {
System.out.println("a is greater than 5");
}
a. a is greater than 5
b. Nothing
c. Error
d. None of the above
166. What is the purpose of the else statement?
a. To execute a statement if the condition in the if statement is false
b. To execute a statement if the condition in the if statement is true
c. To execute a statement if the condition in the if statement is not
met
d. None of the above
167. What is the purpose of the elseif statement?
a. To execute a statement if the condition in the if statement is false
and the condition in the elseif statement is true.
b. To execute a statement if the condition in the if statement is true
and the condition in the elseif statement is false.
c. To execute a statement if the condition in the if statement is not
met and the condition in the elseif statement is met.
d. None of the above
168. Is the below syntax correct for a switch statement?
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
statement;
}
a. Yes b. No
169. What is the purpose of the switch statement?
a. To execute a statement based on the value of an expression
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
170. What is the purpose of the break statement in a switch statement?
a. To prevent the execution of the next case statement
b. To execute the next case statement
c. To execute the default case statement
d. None 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
175. Below syntax is correct for do…while.
do {
statement;
} while (condition);
a. Yes b. No
176. What is the purpose of a do-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
177. Which of the following is a branching statement?
a. break
b. continue
c. return
d. All of the above
178. What is the purpose of the break statement?
a. To terminate a loop
b. To skip to the next iteration of a loop
c. To terminate a method
d. None of the above
179. What is a nested loop?
a. A loop that is contained within another loop
b. A loop that is executed multiple times
c. A loop that is executed until a condition is met
d. None of the above
180. What is the purpose of a nested loop?
a. To execute a statement multiple times within another loop.
b. To execute a statement until a condition is met within another
loop.
c. To execute a statement multiple times and until a condition is met
within another loop.
d. All of the above
181. What are the benefits of using nested loops?
a. To make code more readable and efficient.
b. To execute a statement multiple times within another loop.
c. To execute a statement until a condition is met within another
loop.
d. All of the above
182. What are the drawbacks of using nested loops?
a. To make code less readable and efficient
b. To execute a statement multiple times within another loop
c. To execute a statement until a condition is met within another
loop
d. All of the above
183. What are some examples of when to use nested loops?
a. To iterate over a multidimensional array
b. To perform a binary search
c. To generate a Fibonacci sequence
d. All of the above
184. Can you use a break statement in a switch statement?
a. Yes b. No
185. What is the purpose of using a break statement in a switch
statement?
a. To terminate the switch statement
b. To skip to the next case statement
c. To execute the default case statement
d. None of the above
186. Can you use a continue statement in a switch statement?
a. Yes b. No
187. What is the purpose of using a continue statement in a switch
statement?
a. To terminate the switch statement
b. To skip to the next case statement
c. To execute the default case statement
d. None of the above
188. What is the difference between a break statement and a
continue statement?
a. A break statement terminates a loop or switch statement, while a
continue statement skips to the next iteration of a loop.
b. A break statement skips to the next iteration of a loop, while a
continue statement terminates a loop or switch statement.
c. There is no difference between a break statement and a continue
statement.
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
192. What is the purpose of using a break statement in a nested loop?
a. To terminate the outer loop
b. To terminate the inner loop
c. To skip to the next iteration of the outer loop
d. To skip to the next iteration of the inner loop
193. What is the purpose of using a continue statement in a nested
loop?
a. To terminate the outer loop
b. To terminate the inner loop
c. To skip to the next iteration of the outer loop
d. To skip to the next iteration of the inner loop
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
199. What is the difference between a conditional control flow
statement and an iterative control flow statement?
a. A conditional control flow statement executes a block of code if a
certain condition is met, while an iterative control flow statement
executes a block of code multiple times until a certain condition
is met.
b. An iterative control flow statement executes a block of code if a
certain condition is met, while a conditional control flow
statement executes a block of code multiple times until a certain
condition is met.
c. There is no difference between a conditional control flow
statement and an iterative control flow statement.
d. None 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
202. Which of the following control flow statements can be used to
terminate a loop?
a. break c. return
b. continue d. All of the above
203. Which of the following control flow statements can be used to skip
to the next iteration of a loop?
a. break c. return
b. continue d. None of the above
204. Which of the following control flow statements can be used to
execute a block of code based on the value of an expression?
a. if d. while
b. switch e. both a and b
c. for
205. Which of the following control flow statements can be used to
execute a block of code multiple times until a condition is met?
a. if
b. switch
c. for
d. while
e. both c and d
206. Which of the following control flow statements can be used to
execute a block of code at least once and then multiple times until
a condition is met?
a. do-while c. while
b. for d. All of the above
207. Which of the following control flow statements can be used to
implement the state pattern?
a. if c. for
b. switch d. while
208. Which of the following control flow statements can be used to
implement the strategy pattern?
a. if d. while
b. switch e. both a and b
c. for
209. Which of the following control flow statements can be used to
implement the template method pattern?
a. if d. while
b. switch e. both a and b
c. for
210. Which of the following control flow statements can be used to
implement the binary search algorithm?
a. if d. while
b. switch e. both a and c
c. for
211. Which of the following control flow statements can be used to
implement the merge sort algorithm?
a. if d. while
b. switch e. both c and d
c. for
212. Which of the following control flow statements can be used to
implement the quicksort algorithm?
a. if d. while
b. switch e. a, c and d
c. for
213. Which of the following is a common mistake that people make
when writing control flow statements that can lead to inefficient
code?
a. Not using the appropriate control flow statement for the job
b. Not using break statements to terminate loops when the desired
condition has been met
c. Not using continue statements to skip to the next iteration of a
loop when the desired condition has not been met
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
215. Which of the following control flow statements can be used to
implement a recursive function?
a. if c. for
b. switch d. while
216. Which of the following control flow statements can be used to
implement a lock in concurrent programming?
a. if c. for
b. switch d. while
217. Which of the following control flow statements can be used to
implement a condition variable in concurrent programming?
a. if c. for
b. switch d. while
218. Which of the following control flow statements can be used to
implement a try-catch block?
a. if c. for
b. switch d. while
219. Which of the following control flow statements can be used to
implement a null check?
a. if c. for
b. switch d. while
220. Which of the following control flow statements can be used to
implement a lazy evaluation?
a. if c. for
b. switch d. while
221. Which of the following control flow statements is deterministic?
a. if c. while
b. switch d. All of the above
222. Which of the following control flow statements is non-
deterministic?
a. if c. while
b. switch d. do-while
223. Which of the following control flow statements can be used to
implement a linear search algorithm?
a. if
b. switch
c. for
d. while
224. Which of the following statements is false about the continue
statement?
a. It can be used to skip the rest of the loop body and start the next
iteration.
b. It can be used in any type of loop.
c. It can be used to exit a loop.
d. It can be used to jump to a specific point in the loop body.
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.
226. What is the purpose of the switch statement?
a. To test a variable for equality against a list of values.
b. To execute a block of code based on the value of a variable.
c. To create a menu system.
d. All of the above.
227. What is the correct syntax for the switch statement?
a. switch (variable) {
case value1:
code block 1;
break;
case value2:
code block 2;
break;
...
default:
code block for default case;
}
b. if (variable == value1) {
code block 1;
} else if (variable == value2) {
code block 2;
} else ... else {
code block for default case;
}
c. Both and are correct
d. None of the above
228. What is the difference between a case statement and a default
statement?
a. A case statement is used to test a variable for equality against a
specific value, while a default statement is used to test the
variable for equality against any value.
b. A case statement is used to execute a block of code if the variable
is equal to a specific value, while a default statement is used to
execute a block of code if the variable is not equal to any of the
values in the case statements.
c. Both and are correct.
d. None of the above.
229. Is it necessary to include a break statement after each case
statement?
a. Yes, it is always necessary to include a break statement after each
case statement.
b. No, it is not necessary to include a break statement after each
case statement.
c. It is only necessary to include a break statement after the last case
statement.
d. It is only necessary to include a break statement before the
default statement.
230. What is the output of the following code:
int a = 3;
switch {
case 1:
std::cout<< "One" <<std::endl;
break;
case 2:
std::cout<< "Two" <<std::endl;
break;
case 3:
std::cout<< "Three" <<std::endl;
// No break statement here
default:
std::cout<< "Default" <<std::endl;
}
return 0;
}
a. One
b. Two
c. Three
d. Default
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.
234. Which of the following is a good way to implement a menu system
using the switch statement?
a. Use a separate case statement for each menu option.
b. Use a single case statement with nested if-else statements.
c. Use a while loop with a switch statement inside.
d. All of the above.
235. Which of the following is a good way to test a switch statement?
a. Use unit tests to test each case statement individually.
b. Use integration tests to test the switch statement as part of the
overall program.
c. Use both unit tests and integration tests.
d. None of the above.
236. Which of the following is a good way to document a switch
statement?
a. Use comments to explain the purpose of each case statement.
b. Use a table to show the mapping between the variable being
tested against and the corresponding case statements.
c. Use a state diagram to show the flow of the program through the
switch statement.
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.
238. Which of the following is a good way to implement a state machine
using the switch statement?
a. Use a separate case statement for each state.
b. Use a nested switch statement.
c. Use a goto statement.
d. All of the above.
239. What are the different types of looping statements?
a. for, while, do-while
b. for, if, else
c. for, while, if
d. None of the above
240. Which looping statement is used to execute a block of code a fixed
number of times?
a. for c. do-while
b. while d. All of the above
241. Which looping statement is used to execute a block of code as long
as a condition is true?
a. for c. do-while
b. while d. All of the above
242. Which looping statement is used to execute a block of code at least
once, and then executes it as long as a condition is true?
a. for c. do-while
b. while d. All of the above
243. What is the syntax for a for loop?
for (initialization; condition; increment) {
// code block
}
a. True b. False
244. What is the syntax for a while loop?
while (condition) {
// code block
}
a. True b. False
245. What is the syntax for a do-while loop?
do {
// code block
} while (condition);
a. True b. False
246. What is the difference between a for loop and a while loop?
a. A for loop is used to execute a block of code a fixed number of
times, while a while loop is used to execute a block of code as
long as a condition is true.
b. A for loop is used to execute a block of code as long as a
condition is true, while a while loop is used to execute a block of
code a fixed number of times.
c. There is no difference between a for loop and a while loop.
d. None of the above
247. What is the difference between a while loop and a do-while
loop?
a. A while loop executes the code block at least once, while a do-
while loop executes the code block at least once and then as long
as the condition is true.
b. A do-while loop executes the code block at least once, while a
while loop executes the code block at least once and then as long
as the condition is true.
c. There is no difference between a while loop and a do-while loop.
d. None 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
1 c 51 b 101 d 151 a 201 d
2 b 52 c 102 d 152 b 202 d
3 c 53 b 103 d 153 a 203 b
4 a 54 c 104 a 154 a 204 e
5 d 55 b 105 d 155 a 205 e
6 c 56 d 106 c 156 a 206 a
7 a 57 c 107 c 157 d 207 b
8 d 58 d 108 d 158 a 208 e
9 b 59 d 109 d 159 k 209 e
10 c 60 b 110 d 160 a 210 e
11 a 61 d 111 d 161 a 211 e
12 c 62 b 112 d 162 a 212 e
13 a 63 c 113 d 163 a 213 d
14 b 64 c 114 d 164 d 214 d
15 a 65 a 115 d 165 a 215 d
16 b 66 d 116 b 166 a 216 d
17 b 67 b 117 d 167 a 217 d
18 b 68 a 118 d 168 a 218 a
19 c 69 b 119 d 169 a 219 a
20 a 70 b 120 b 170 a 220 d
21 b 71 a 121 d 171 a 221 d
22 d 72 c 122 d 172 a 222 d
23 b 73 a 123 d 173 a 223 c
24 c 74 c 124 c 174 a 224 d
25 b 75 a 125 d 175 a 225 d
26 b 76 d 126 d 176 a 226 d
27 c 77 b 127 d 177 d 227 c
28 d 78 b 128 a 178 a 228 c
29 d 79 b 129 b 179 a 229 a
30 c 80 a 130 a 180 d 230 d
31 a 81 b 131 a 181 d 231 b
32 b 82 b 132 d 182 a 232 b
33 d 83 b 133 a 183 d 233 d
34 a 84 a 134 a 184 a 234 a
35 a 85 a 135 d 185 a 235 c
36 c 86 b 136 d 186 b 236 d
37 a 87 a 137 a 187 d 237 a
38 a 88 d 138 a 188 a 238 a
39 a 89 a 139 b 189 a 239 a
40 c 90 a 140 d 190 d 240 a
41 b 91 a 141 a 191 d 241 b
42 b 92 a 142 d 192 b 242 c
43 b 93 d 143 d 193 d 243 a
44 c 94 a 144 a 194 d 244 a
45 b 95 a 145 a 195 d 245 a
46 a 96 f 146 a 196 d 246 a
47 d 97 b 147 d 197 d 247 a
48 d 98 d 148 a 198 d 248 c
49 b 99 f 149 a 199 a 249 c
50 d 100 b 150 b 200 d 250 c
CHAPTER 5
Functions
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.
Multiple choice questions
1. What is the purpose of a Python function?
a. To print text on the screen
b. To store data
c. To perform a specific task or set of tasks
d. To create a loop
2. In Python, how do you define a function?
a. Using the ‘def’ keyword followed by the function name and
parameters
b. Using the function keyword followed by the function name
c. Using the define keyword followed by the function name and
parameters
d. Functions are defined automatically
3. What is a parameter in a Python function?
a. A variable used to store the result of the function
b. A variable used to store the function name
c. A value passed to the function when it is called
d. A reserved keyword in Python
4. Which keyword is used to return a value from a Python function?
a. result c. return
b. break d. output
5. What is the purpose of the None keyword in Python functions?
a. It is used to define a function that does nothing.
b. It is used to specify the end of a function.
c. It represents a missing or undefined value.
d. It is a syntax error in Python.
6. What is a recursive function in Python?
a. A function that calls itself
b. A function that uses loops instead of recursion
c. A function that takes no arguments
d. A function that uses the recursion keyword
7. What is the scope of a variable declared inside a Python function?
a. Global scope
b. Local scope
c. Both global and local scope
d. No scope
8. Which of the following is NOT a valid way to pass arguments to a
Python function?
a. Positional arguments
b. Keyword arguments
c. Default arguments
d. Variable arguments
9. What is a lambda function in Python?
a. A function that can be called without parentheses
b. A function that is defined using the def keyword
c. An anonymous function defined using the lambda keyword
d. A built-in Python function
10. Which of the following is used to call a Python function?
a. call()
b. invoke()
c. run()
d. The function name followed by parentheses, e.g.,
function_name()
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):
13. In Python, can a function have multiple return statements?
a. Yes, but only if they return different data types.
b. Yes, but only if they are placed within a loop.
c. No, a function can only have one return statement.
d. Yes, and they can be placed anywhere in the function.
14. What is the purpose of the pass statement in Python functions?
a. To stop the execution of the program
b. To indicate that the function should be skipped
c. To define an empty function or block of code
d. To print a message to the console
15. What is the difference between a function definition and a function
call?
a. A definition creates a function, and a call executes it
b. A definition executes a function, and a call creates it
c. There is no difference between them
d. A definition and a call are the same thing
16. What is the scope of a variable declared outside of all functions in
a Python script?
a. A definition creates a function, and a call executes it
b. A definition executes a function, and a call creates it
c. There is no difference between them
d. A definition and a call are the same thing
17. Which keyword is used to pass a variable by reference to a Python
function?
a. pass
b. byref
c. ref
d. Python always passes variables by reference
18. What is the purpose of the *args parameter in a Python function
definition?
a. To specify default arguments
b. To allow the function to accept a variable number of positional
arguments
c. To allow the function to accept keyword arguments
d. To specify required arguments
19. Which of the following is not a valid way to call a function with
keyword arguments in Python?
a. function_name(arg1=value1, arg2=value2)
b. function_name(value1, value2)
c. function_name(arg2=value2, arg1=value1)
d. function_name(value2, arg1=value1)
20. What does the **kwargs parameter in a Python function
definition allow you to do?
a. Specify default keyword arguments
b. Accept a variable number of keyword arguments
c. Define a function with any number of arguments
d. Pass keyword arguments as a list
21. Python function always returns a value.
a. True b. False
22. What is the output of the add() function call?
def add(a, b):
return a+5, b+5
result = add(3,2)
print(result)
a. 15 c. (8,7)
b. 8 d. Syntax Error
23. Given the following function fun1() Please select all the correct
function calls:
def fun1(name, age):
print(name, age)
a. fun1(name = “Emma”, 23)
b. fun1(age= 23, “Emma”)
24. What is the output of the following code?
def outer_fun(a, b):
def inner_fun(c, d):
return c + d
return inner_fun(a, b)
res = outer_fun(5,10)
print(res)
a. 15
b. Syntax Error
c. (5,10)
25. Choose the correct function declaration of fun1() so that we can
execute the following function call successfully:
fun1(25,75,55)
fun1(10,20)
a. def fun1(**kwargs)
b. No, it is not possible in Python
c. Def fun1(args*)
d. Def fun1(*data)
26. What is the output of the following function call:
def fun1(name, age=20):
print(name, age)
fun1('Emma',25)
a. Emma 25
b. Emma 20
27. What is the output of the following function call:
def fun1(num):
return num +25
fun1(5)
print(num)
a. 25
b. 5
c. NameError
d. 30
28. Select which if the following is true for Python function:
a. A function is a code block that only executes when called and
always returns a value.
b. A function only executes when it is called and we can reuse it in
a program
c. Python doesn’t support nested function
d. All of above
29. What is the output of the following display_person() function
call:
def display_person(*args):
for i in args:
print(i)
display_person(name="Emma", age="25")
a. TypeError
b. Emma
25
c. name
age
30. What is the output of the following display() function call:
def display(**kwargs):
for i in kwargs:
print(i)
display(emp="Kelly", salary=9000)
a. TypeError
b. Kelly
9000
c. (‘ emp’, ‘Kelly’)
(‘salary’, 9000)
d. emp
salary
31. What is the output of the following function call:
def outer_fun(a, b):
def inner_fun(c, d):
return c + d
return inner_fun(a, b)
return a
result = outer_fun(5,10)
print(result)
a. 5 c. (5,15)
b. 15 d. Syntax Error
32. Which keyword is used for function?
a. Define c. Def
b. Fun d. Function
33. Which of the following items are present in the function header?
a. function name c. return value
b. parameter list d. Both a and b
34. If return statement is not used inside the function, the function will
return:
a. None c. Null
b. 0 d. Arbitary value
35. In which part of memory does the system stores the parameter
and local variables of function call?
a. Heap
b. Stack
c. Uninitialized data segment
d. None of the above
36. Lambda is a function in Python.
a. True
b. False
c. Lambda is a function in Python but user cannot use it.
d. None of the above
37. What is a variable defined outside a function referred to as?
a. Local variable c. Static variable
b. Global variable d. Automatic variable
38. What is the output of the following program:
z = lambda x : x * x
print(z(6))
a. 6 c. 0
b. 36 d. error
39. How is a function declared in Python?
a. def function function_name():
b. declare function function_name():
c. def function_name():
d. declare function_name():
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()
41. Which one of the following is incorrect?
a. The variables used inside function are called local variables.
b. The local variables of a particular function can be used inside
other functions, but these cannot be used in global space
c. The variables used outside function are called global variables
d. In order to change the value of global variable inside function,
keyword global is used.
42. Function blocks begin with the keyword?
a. Define c. Function
b. Fun d. Def
43. A return statement with _____ arguments.
a. No c. 2
b. 1 d. Any
44. ___________ are the arguments passed to a function in correct
positional order.
a. Required arguments
b. Keyword arguments
c. Default arguments
d. Variable-length arguments
45. In a program, a function can be called __________ times.
a. 2 c. 5
b. 3 d. Multiple times
46. Which of the following statement is a function call?
a. call sum() c. sum()
b. def sum() d. function sum()
47. Which of the following are advantages of using function in
program?
a. It increases readability of program
b. It increase reusability
c. It makes debugging easier
d. All of the above
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
49. The function can be called in the program by writing function
name followed by ____.
a. []
b. {}
c. ()
d. None of the above
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
60. Write the output of the following:
print("A")
def prnt():
print("B")
print("C")
prnt()
a. A B C c. A B
b. B C A d. A C B
61. Which module is to be imported for using randit() function?
a. rand c. Randrange
b. Random d. Randomrange
62. Choose the incorrect statement:
a. print(pow(2,3))
b. print(pow(2.3,3.2))
c. print(pow(2,3,2))
d. None of the above
63. What is the purpose of a Python function?
a. To store data
b. To perform a specific task or calculation
c. To define a class
d. To write comments
64. Which of the following is true about Python function names?
a. Function names must start with a capital letter
b. Function names are case-sensitive
c. Function names cannot contain numbers
d. Function names can contain spaces
65. What is the result of the following Python function definition?
def greet(name):
print(f"Hello, {name}!")
a. It defines a function that takes an argument ‘name’ and prints a
greeting.
b. It defines a variable ‘name’ and prints a greeting.
c. It defines a class called ‘greet’ with a method.
d. It defines a lambda function.
66. In Python, can a function return multiple values?
a. No, a function can only return a single value.
b. Yes, a function can return a tuple of values.
c. Yes, a function can return a list of values.
d. Yes, a function can return multiple values separated by commas.
67. What is the scope of a variable defined inside a Python function?
a. It is a global variable.
b. It can only be accessed within the function
c. It can be accessed both inside and outside the function.
d. It depends on the function’s name.
68. Which keyword is used to define a default value for a function
parameter in Python?
a. default c. value
b. def d. none
69. How can you call a Python function with named arguments?
a. By using square brackets
b. By using curly braces
c. By using parentheses and specifying the parameter names
d. By using angle brackets
70. What is the purpose of the return statement in a Python function?
a. It is used to exit the program.
b. It is used to print a value.
c. It is used to define a variable.
d. It is used to return a value from the function.
71. In Python, can you define a function inside another function?
a. Yes, it is called a nested function.
b. No, Python does not support nested functions.
c. Only if the outer function is a lambda function.
d. Only if the inner function is a generator function.
72. What is the difference between a function definition and a function
call in Python?
a. There is no difference.
b. A function definition defines the function’s behavior, while a
function call executes the defined behavior.
c. A function definition specifies the arguments, while a function
call specifies the function’s name.
d. A function call is used to create a new function.
73. In Python, can a function be defined without any parameters?
a. No, every function must have at least one parameter.
b. Yes, a function can be defined without any parameters.
c. Only if the function is a lambda function.
d. Only if the function is an anonymous function.
74. What is the purpose of the pass statement in Python?
a. It is used to skip a loop iteration.
b. It is used to raise an exception.
c. It is used to define a new variable.
d. It is a placeholder for future code and does nothing.
75. Which of the following statements is true about function names in
Python?
a. Function names can contain spaces.
b. Function names can start with a digit.
c. Function names can include special characters like %, @, and #.
d. Function names should follow the same naming rules as variable
names.
76. Which of the following is a valid way to call a Python function
named my_function with two arguments?
a. call my_function(1, 2)
b. my_function(1, 2)
c. my_function(1 2)
d. call my_function 1, 2
77. Which keyword is used to indicate that a variable in a function is
not a local variable but a reference to a global variable?
a. Local c. Scope
b. Global d. Variable
78. What is the result of calling the len() function on a string in
Python?
a. It returns the number of characters in the string.
b. It returns the number of words in the string.
c. It returns the last character of the string.
d. It returns the string reversed.
79. What does the None keyword represent in Python?
a. It represents an empty string.
b. It represents a zero value.
c. It represents the absence of a value or a null value.
d. It represents a positive integer.
80. Which of the following is a valid way to return multiple values
from a Python function?
a. By using a list
b. By using a tuple
c. By using a dictionary
d. Only one value can be returned from a function
81. In Python, can you define a function inside another function?
a. Yes, it is called a nested function.
b. No, Python does not support nested functions.
c. Only if the outer function is a lambda function.
d. Only if the inner function is a generator function.
82. What is the purpose of the **kwargs parameter in a Python
function?
a. It allows the function to accept keyword arguments as a
dictionary.
b. It defines default keyword arguments.
c. It is used to specify the order of keyword arguments.
d. It is not a valid parameter in Python functions
83. What is a docstring in Python?
a. A data type used to store strings
b. A type of comment used in code
c. A string literal that appears at the beginning of a function to
provide documentation
d. A keyword used to format strings
84. What does the enumerate() function do in Python?
a. It counts the number of characters in a string.
b. It creates an enumerated list of items.
c. It generates a sequence of numbers.
d. It raises an exception.
85. In Python, what is the purpose of the if __name__ ==
"__main__": block?
a. It is used to define a main function.
b. It is a code comment.
c. It is used to check if a variable is defined.
d. It ensures that the code is executed only when the script is run as
the main program and not when it is imported as a module.
86. What is a function signature in Python?
a. It is a unique name for a function.
b. It is a special character used in function names.
c. It is a keyword used to define a function.
d. It is not a concept in Python.
87. Which Python built-in function is used to calculate the length of a
sequence (e.g., a string, list, or tuple)?
a. size() c. len()
b. length() d. count()
88. What does the abs() function do in Python?
a. It returns the absolute value of a number
b. It converts a string to uppercase
c. It removes leading and trailing spaces from a string
d. It checks if a string contains only alphabetic characters
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
91. What is the purpose of the input() function in Python?
a. It prints text to the console.
b. It reads user input from the keyboard.
c. It converts a string to an integer.
d. It generates random numbers.
92. What does the round() function do in Python?
a. It rounds a number to the nearest integer.
b. It returns the square root of a number.
c. It generates random numbers.
d. It calculates the factorial of a number.
93. Which built-in function is used to convert a number to a string?
a. str()
b. int_to_str()
c. number_to_string()
d. convert_string()
94. What does the sum() function do in Python?
a. It returns the product of all elements in a list.
b. It calculates the sum of all elements in an iterable.
c. It computes the difference between two numbers.
d. It returns the maximum element in a list.
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.
97. Which built-in function is used to check if a value is within a
specified range?
a. range() c. is_within()
b. in_range() d. between()
98. What does the any() function do in Python?
a. It checks if a value is greater than another value.
b. It checks if all elements in an iterable are True.
c. It returns the first element of an iterable.
d. It converts a string to lowercase.
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()
102. What does the max() function do in Python?
a. It returns the smallest value from a list.
b. It finds the maximum value from an iterable (e.g., list, tuple).
c. It counts the number of elements in an iterable.
d. It calculates the average of a sequence of numbers.
103. What is the purpose of the min() function in Python?
a. To find the smallest value in a list
b. To calculate the average of a list of numbers
c. To generate random integers
d. To convert a string to lowercase
104. Which Python built-in function is used to convert a number to a
string?
a. numToStr()
b. numberToString()
c. str()
d. intToStr()
105. What is the primary purpose of the input() function in
Python?
a. To print text to the console
b. To read user input from the keyboard
c. To perform mathematical calculations
d. To format strings
106. What does the round() function do in Python?
a. It calculates the square root of a number.
b. It performs string concatenation.
c. It rounds a number to the nearest integer.
d. It converts a number to a string.
107. Which built-in function is used to check if a value is a specific type
(e.g., int, str)?
a. typeof() c. isinstance()
b. check_type() d. type_check()
108. What does the sum() function do in Python?
a. It returns the product of all elements in a list.
b. It computes the difference between two numbers.
c. It calculates the sum of all elements in an iterable.
d. It counts the number of elements in a list.
109. Which built-in function is used to check if a value is within a
specified range?
a. range_check() c. between()
b. in_range() d. within_range()
110. What is the purpose of the any() function in Python?
a. It returns true if all elements in an iterable are True.
b. It converts a string to uppercase.
c. It checks if at least one element in an iterable is True.
d. It performs string splitting.
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.
113. What does the chr() function do in Python?
a. It calculates the character’s checksum.
b. It converts a character to its Unicode code point.
c. It returns the next character in the ASCII sequence.
d. It checks if a character is a vowel.
114. Which built-in function is used to capitalize the first letter of a
string in Python?
a. capitalize()
b. upper()
c. title()
d. first_letter()
115. What does the ord() function do in Python?
a. It calculates the absolute value of a number.
b. It converts a character to its ASCII code.
c. It returns the last character in a string.
d. It finds the highest value in a list.
116. Which built-in function is used to remove leading and trailing
spaces from a string in Python?
a. strip()
b. clean()
c. trim()
d. remove_spaces()
117. What is the purpose of the sorted() function in Python?
a. It generates random numbers.
b. It calculates the square root of a number.
c. It sorts the elements of an iterable (e.g., list) in ascending order.
d. It creates a new list.
118. Which built-in function is used to check if all characters in a string
are alphabetic?
a. is_alpha() c. all_alpha()
b. check_alpha() d. alphabetic()
119. What does the format() function do in Python?
a. It calculates the square of a number.
b. It formats a string according to specified format codes.
c. It generates random numbers.
d. It checks if a string is in lowercase.
120. Which built-in function is used to find and replace a substring in a
string?
a. find() c. search()
b. replace() d. substring()
121. Which built-in function is used to check if all characters in a string
are digits?
a. is_digit() c. all_digits()
b. check_digits() d. digit_check()
122. What is the primary purpose of the list() function in Python?
a. To create a list from an iterable (e.g., string, tuple)
b. To perform list concatenation
c. To find the maximum element in a list
d. To remove an element from a list
123. Which built-in function is used to convert a string to lowercase in
Python?
a. convert_lowercase()
b. lower()
c. to_lower()
d. casefold()
124. What does the map() function do in Python?
a. It performs list sorting.
b. It applies a function to all items in an iterable and returns an
iterator.
c. It calculates the square root of a number.
d. It generates a sequence of numbers.
125. Which built-in function is used to calculate the power of a
number?
a. power()
b. pow()
c. calculate_power()
d. exp()
126. What is the primary purpose of the range() function in
Python?
a. To perform arithmetic operations on a sequence of numbers
b. To check if a value is within a specified range
c. To generate a sequence of numbers within a specified range
d. To find the maximum value in a list
127. What is the primary purpose of the zip() function in Python?
a. To zip and compress files.
b. To combine multiple iterables into a single iterable of tuples.
c. To generate random integers.
d. To extract files from a zip archive.
128. Which built-in function is used to split a string into a list of
substrings based on a specified delimiter?
a. split() c. substring()
b. delimiter() d. split_string()
129. What does the hex() function do in Python?
a. It converts a string to hexadecimal format.
b. It returns the absolute value of a number.
c. It converts an integer to a hexadecimal string.
d. It calculates the square root of a number.
130. Which built-in function is used to convert a string to title case
(capitalizing the first letter of each word)?
a. to_title_case() c. capitalize_words()
b. title() d. title_case()
131. What is the primary purpose of the filter() function in
Python?
a. To filter and compress data
b. To remove specific elements from a list based on a condition
c. To create a filtered copy of a list
d. To calculate the average of a list of numbers
132. Which built-in function is used to count the number of
occurrences of a specified element in a list?
a. count() c. element_count()
b. find_count() d. occurrences()
133. Which built-in function is used to check if a string starts with a
specified prefix?
a. start_with() c. startswith()
b. prefix() d. begin_with()
134. What is the primary purpose of the sorted() function with a
custom key function in Python?
a. To sort a list in descending order.
b. To filter out specific elements from a list.
c. To sort a list using a custom comparison function.
d. To create a copy of a list.
135. Which built-in function is used to check if a value is even?
a. even() c. check_even()
b. is_even() d. even_number()
136. What does the next() function do in Python?
a. It returns the previous element in a sequence.
b. It generates random numbers.
c. It calculates the square root of a number.
d. It returns the next item from an iterator.
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()
140. What is the purpose of the complex() function in Python?
a. To create complex numbers with real and imaginary parts.
b. To convert a complex number to an integer.
c. To calculate the square root of a complex number.
d. To round a complex number to the nearest integer.
141. Which built-in function is used to reverse the order of elements in
a list?
a. reverse() c. invert()
b. revert() d. flip()
142. Which built-in function is used to check if a string ends with a
specified suffix?
a. end_with() c. endswith()
b. suffix() d. finish_with()
143. Which built-in function is used to check if a value is a prime
number?
a. is_prime()
b. prime_number()
c. check_prime()
d. prime_check()
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.
145. Which built-in function is used to check if a string is a
palindrome?
a. is_palindrome()
b. palindromic()
c. check_palindrome()
d. palindrome_check()
146. Which built-in function is used to count the number of
occurrences of a substring in a string?
a. count()
b. substring_count()
c. string_count()
d. find_count()
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()
148. What is the purpose of the int() function in Python?
a. To check if a value is an integer.
b. To convert a floating-point number to an integer.
c. To calculate the absolute value of a number.
d. To perform integer division.
149. Which built-in function is used to convert a string to uppercase in
Python?
a. convert_uppercase()
b. upper()
c. to_upper()
d. uppercase()
150. What does the max() function do in Python when applied to a
string?
a. It returns the smallest character in the string.
b. It calculates the sum of ASCII values of characters.
c. It finds the maximum character based on their ASCII values.
d. It converts the string to title case.
151. What is the primary purpose of defining a user-defined function in
Python?
a. To check if a value is even or odd.
b. To create custom data types.
c. To encapsulate a block of code for reuse.
d. To perform arithmetic operations on variables.
152. What is a “docstring” in Python functions?
a. It is a data type for storing strings.
b. It is a string containing documentation for the function.
c. It is a type of loop construct in Python.
d. It is a keyword used to define the function.
153. In Python, can a function have multiple return statements within
it?
a. Yes, but only if each return statement has a different variable
name.
b. Yes, and the function will return the value from the first executed
return statement.
c. No, a function can only have one return statement.
d. Yes, and the function will return the value from the last executed
return statement.
154. What is a “function call” in Python?
a. It is the process of defining a function.
b. It is a built-in function used to call other functions.
c. It is the execution of a user-defined function by specifying its
name and passing arguments.
d. It is the process of creating a function’s docstring.
155. What is the purpose of the join() function 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.
156. What does the ord() function do in Python?
a. It calculates the absolute value of a number.
b. It converts a character to its ASCII code.
c. It returns the last character in a string.
d. It converts a number to a string.
157. Which built-in function is used to remove leading and trailing
spaces from a string in Python?
a. trim()
b. strip()
c. remove_spaces()
d. clean()
158. What does the format() function do in Python?
a. It calculates the square root of a number.
b. It performs string concatenation.
c. It formats a string according to specified format codes.
d. It generates random numbers.
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.
161. Which built-in function is used to check if a value is a specific type
(e.g., int, str)?
a. typeof() c. isinstance()
b. check_type() d. type_check()
162. What is the primary purpose of the list() function in Python?
a. To create a list from an iterable (e.g., string, tuple).
b. To perform list concatenation.
c. To find the maximum element in a list.
d. To remove an element from a list.
163. Which built-in function is used to calculate the square root of a
number in Python?
a. sqrt() c. root()
b. square_root() d. math.sqrt()
164. What is the purpose of the dir() function in Python?
a. To create a directory in the file system.
b. To remove a directory.
c. To list the names of attributes and methods of an object.
d. To check if a file exists.
165. Which built-in function is used to check if all characters in a string
are digits?
a. is_digit() c. all_digits()
b. check_digits() d. digit_check()
166. Which built-in function is used to find the index of the last
occurrence of a specified element in a list?
a. find_last_index()
b. last_index()
c. search_last()
d. rindex()
167. What is the primary purpose of the str() function in Python?
a. To calculate the sum of all elements in an iterable
b. To convert a string to lowercase
c. To convert a value to a string
d. To generate random strings
168. What is the purpose of the float() function in Python?
a. To convert a value to a floating-point number.
b. To find the maximum value in a list.
c. To generate random floating-point numbers.
d. To calculate the average of a list of numbers.
169. What will be the output of the code?
def sayHello():
print('Hello World!')
sayHello()
sayHello()
a. Hello WorldHello World!
b. ‘Hello World!” Hello World!’
c. Hello Hello
d. None
170. What will be the output of the following code?
def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
a. 3
b. 4
c. 4 is maximum
d. None
171. What will be the output of the following code?
x =50
def func(x):
print('x is', x)
x =2
print('Changed local x to', x)
func(x)
print('x is now', x)
a. x is 50 Changed local x to 2
X is now 50
b. x is 50
Changed local x to 2
X is now 2
c. x is 50
Changed local x to 2
X is now 100
d. None of the mentioned
172. What will be the output of the following code?
x =50
def func():
global x
print('x is', x)
x =2
print('Changed global x to', x)
func()
print('Value of x is', x)
a. x is 50
Changed global x to 2
Value of x is 50
b. x is 50
Changed global x to 2
Value of x is 2
c. x is 50
Changed global x to 50
Value of x is 50
d. None
173. What will be the output of the following code?
def say(message, times =1):
print(message * times)
say('Hello')
say('World',5)
a. Hello
WorldWorldWorldWorldWorld
a. Hello
World 5
b. Hello
world,World,World,World,World
c. Hello
HelloHelloHelloHelloHello
174. What will be the output of the following code:
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is',
c)
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
175. What will be the output of the following code:
def maximum(x, y):
if x > y:
return x
elif x == y:
return'The numbers are equal'
else:
return y
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
177. Write the output of the following:
t= sum(32,34,33,33.5,41,44,33)
print(sum (t)+t.count(33))
a. 252.0 c. 252.5
b. 253.0 d. 254
178. What will be returned after calling modulus (100,95) and modulus
(95.3,100.5) and modulus (12,12)?
def modulus(num1,num2):
answer=num1%num2
return answer
a. 5 and 5.2 and 1
b. 5 and 95.3 and 0
c. 100 and 95.3 and 12
d. 95 and 100.5 and 0
e. 5 and 100.5 and 1
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).
181. What would be outputted after running the code below:
def addition(num1,num2):
return(num1+num2)
def subtraction(num1,num2):
print(num1-num2)
def main():
add_answer=addition(2,4)
new _add_answer=addition(add_answer,105)
print(subtraction(new_add_answer,200))
a. None and -89 c. -89
b. None d. -89 and None
182. What will be printed when the following code executes:
def test(a,b=5):
print(a,b)
test(-3)
a. a,b d. -3,5
b. -3,b e. -3 5
c. A,5
183. What will the following Python program print out?
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
a. Zap ABC jane fred jane
b. Zap ABC Zap
c. ABC Zap jane
d. ABC Zap ABC
e. Zap Zap Zap
184. What value is printed when the following code is executed?
name="Jane Doe"
def myFunction(parameter):
value="First"
value=parameter
print(value)
myFunction("Second")
a. Value d. First
b. Second e. Jane Doe
c. Parameter
185. A named sequence of statements is known as which of the
following?
a. Definition d. Module
b. Method e. Function
c. Turtle
186. What will the following code print?
def pow(b,p):
y=b**p
return y
def square(x):
a=pow(x,2)
return a
n=5
result=square(n)
print(result)
a. 5 d. 32
b. 10 e. 3125
c. 25
187. Consider the following Python code.
def rem(a,b):
return a%b
print(rem(3,7))
What does this code print?
a. 0 c. 7
b. 3 d. 1
188. Which of the following would NOT work as a variable name?
a. a c. length
b. len d. x
189. Consider the code below. What prints?
print(int(33.7))
a. 34.0 c. 33.70
b. 34 d. 33
190. Consider the code below. Line 1 is called:
def printWeather():
print("It is sunny!")
a. the function header
b. the function body
c. the function definition
d. the function named
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.
192. cal(n1) : What is n1?
a. Parameter c. Keyword
b. Argument d. None
193. Write the output of the code?
def s(n1):
print(n1)
n2=4
s(n2)
a. 2 c. 4
b. 3 d. Error
194. Which of the following statement will execute in the last?
def s(n1): #statement 1
print(n1) #statement 2
n2=4#statement 3
s(n2) #statement 4
a. Statement 1 c. Statement 3
b. Statement 2 d. Statement 4
195. Write the output of the following code:
def s(n1):
print(n1)
n1=n1+2
n2=4
s(n2)
print(n2)
a. 6 4 c. 4 4
b. 4 6 d. 6 6
196. Consider the following code and choose the incorrect statement:
def s(n1):
print(id(n1))
n2=4
s(n2)
print(id(n2))
a. Function name is ‘s’
b. Function’ s’ is taking one parameter
c. Both print statement will print the same value
d. Both print statement will print different value
197. Write the output of the following code:
def call(m,n):
if m==n:
return m*3
else:
return m*2
s=call(9,8)
print(s)
a. 16 b. 18
c. 27 d. 24
198. Write the output of the following code:
def call(m,n):
if m==n:
return m*3
else:
return m*2
s=call("Amit"," Anuj")
print(s)
a. AmitAmitAmit c. AnujAnujAnuj
b. AmitAmit d. AnujAnuj
199. Write the output of the following code:
def fn(n1, n2=7):
n1=n1+n2
print(n1)
fn(3,9)
a. 3 c. 12
b. 9 d. 10
200. Write the output of the following code:
def fn(n1, n2=7):
n1=n1%n2
print(n1)
fn(3%2,9%2)
a. 1 c. 2
b. 0 d. 3
201. Which of the following function definition header is wrong?
a. def sum(n1,n2,n=3):
b. def scan(p1,p2=4,p3=5):
c. def div(p1=4,p2,p3):
d. def mul(p1,n1,m1):
202. Function which does not return any value is called____.
a. Default function c. Void function
b. Zero function d. Null function
203. The ____ statement returns the values from the function to the
calling function.
a. send c. return
b. give d. take
204. The return statement in function is used to ___.
a. return value
b. return the control to the calling function
c. Both of the above
d. None
205. 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.
c. We can create function with arguments and no return value.
d. All of the above
206. Write the output of the following code:
sound()
def sound():
print("sound"*2)
a. sound
b. soundsound
c. Name error:name ‘sound’ is not defined
d. SyntaxError:invalid syntax
207. Write the output of the following code:
a=9
def sound():
b=7
print(a)
sound()
print(b)
a. 7 7 c. 7 9
b. 9 9 d. Error
208. 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
209. Which of the following is not the built-in function?
a. input() c. print()
b. tuple() d. dictionary()
210. Which of the following is not the type of function argument?
a. Required argument
b. Keyword argument
c. Initial argument
d. Default argument
211. Write the output of the following code:
print("A")
def prnt():
print("B")
print("C")
prnt()
a. A B C c. A B
b. B C A d. A C B
212. Which module is to be imported for suing randit() function?
a. rand c. randrange
b. random d. Randomrange
213. Which of the following number can never be generated by the
following code:
random.randrange(0,100)
a. 0 c. 99
b. 100 d. 1
214. Write the output of the following code:
print(abs(-45))
a. 45.0 c. 45
b. -45 d. None
215. Write the output of the following code:
print(max[1,2,3,4],[4,5,6],[7])
a. [1,2,3,4] c. [7]
b. [4,5,6] d. 7
216. Write the output of the following code:
print(min(tuple("computer")))
a. c c. u
b. o d. t
217. Choose the incorrect statement:
a. print(pow(2,3))
b. print(power(2.3 , 3.2))
c. print(pow(2,3,2))
d. None
218. Which of the following statement is correct?
a. A python standard library consists of a number of modules.
b. A module consists of a number of Python standard libraries.
c. Library and modules are alias of each other.
d. None
219. Write the output of the following code?
print(math.floor(-4.5))
a. -4 c. 4
b. -5 d. 5
220. _________ function of math module calculates the factorial.
a. fact() c. factorial()
b. facto() d. factor()
221. Smallest number return by statement
random.randrange(2,7) is _______.
a. 2 c. -2
b. 7 d. 0
222. Which of the following components are a part of a function header
in Python?
1 Function name
2 Return statement
3 Parameter list
4 Def keyword
a. Only 1 c. 3 and 4
b. 1 and 3 d. 1 , 3 and 4
223. Which of the following function headers is correct?
a. def cal_si(p=100,r,t=2) :
b. def cal_si(p=100,r=8,t) :
c. def cal_si(p,r=8,t) :
d. def cal_si(p,r=8,t=2) :
224. Which of the following is the correct way to call a function?
a. my_func() c. return my_func
b. def my_func() d. call my_func()
225. What is the output of the following code:
def add(num1, num2):
Sum=num1+num2
sum=add(20,30)
print(sum)
a. 50
b. 0
c. Null
d. None
226. Functions created by user is called ____________.
a. Inbuilt c. User defined
b. Library d. Logical
227. Division of larger programs into smaller programs. These smaller
programs are called_____.
a. Functions c. Logical programs
b. Operators d. Specific programs
228. Use of function ______ the size of programs.
a. Increases
b. Reduces
c. Makes no change in
d. None
229. We must import a specific module for suing built-in functions?
a. True b. False
230. A function can be called ____ times in a program.
a. 3 c. 4
b. 7 d. Any number
231. Which of the following is not a type conversion functions?
a. int() c. input()
b. str() d. float()
232. Write the output of the following code:
print(int())
a. Error
b. Any random number
c. 0
d. 1
233. Which of the following statement will return error?
print(int("a"))
print(str(123))
a. statement 1
b. statement 2
c. Both statement
d. None
234. Write the output of the following code:
print(float())
a. 1.0
b. 0.0
c. Any floating number
d. Any integer
235. What type of error is returned by following statement?
print(int("a"))
a. Syntax Error c. Type Error
b. Value Error d. Name Error
236. Write the output if the user enters 7:
a = input("Enter age")
print(type(a))
a. str c. float
b. int d. None
237. Write the output of the following code:
print(max(2,5,4,8,29,24))
a. Error as there should be math.max()
b. 29
c. 2
d. 2 5 4 8 29 24
238. Write the output of the following code:
print(min ("Hell", "Hello", "he"))
a. Hell c. Hello
b. He d. Error
239. abs() function do not work for float number.
a. True b. False
240. Write the output:
print(abs (-8))
a. -8 c. 8.0
b. 8 d. None
241. len() function returns only the length of string.
a. True b. False
242. Write the output of the following code:
print(range (5))
a. range(0,5) c. [0,1,2,3,4]
b. 0,1,2,3,4 d. Error
243. Name the function required to check if a string contains only
uppercase letters?
a. upper() c. isupper()
b. isup() d. iscapital()
244. What is the output of the following code:
all([2,4,0,6])
a. Error c. False
b. True d. 0
245. Which of the following function returns the length of the
sequence?
a. len() c. lenseq()
b. length() d. None
246. Which of the following function is not invoked by math module?
a. ceil() c. sqrt()
b. floor() d. mean()
247. Write the output of the following code:
print(sum (1,2,1))
a. Error c. 2
b. 4 d. 3
248. Which of the following module is used for function max()?
a. math
b. csv
c. random
d. No module is required
249. Write the output of the following code:
def c(x,y):
if x%y:
return x+5
else:
return y+10
print(c(20,5))
a. 26 c. 30
b. 15 d. 10
250. Write the output of the following code:
def calc(x):
r=2*x**2
return r
print(cal(3))
a. 18 c. 36
b. 8 d. 9
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 c 51 c 101 d 151 c 201 c
2 a 52 d 102 b 152 b 202 c
3 c 53 b 103 a 153 d 203 c
4 c 54 a 104 c 154 c 204 a
5 c 55 c 105 b 155 d 205 d
6 a 56 b 106 c 156 b 206 c
7 b 57 c 107 c 157 b 207 d
8 b 58 d 108 c 158 c 208 c
9 c 59 c 109 b 159 b 209 d
10 d 60 a 110 c 160 c 210 c
11 a 61 b 111 b 161 c 211 a
12 b 62 c 112 c 162 a 212 b
13 d 63 b 113 b 163 d 213 b
14 c 64 b 114 a 164 c 214 c
15 a 65 a 115 b 165 a 215 c
16 a 66 b 116 a 166 d 216 a
17 d 67 b 117 c 167 c 217 b
18 b 68 d 118 a 168 a 218 a
19 b 69 c 119 b 169 a 219 b
20 b 70 d 120 b 170 c 220 c
21 b 71 a 121 a 171 a 221 a
22 c 72 b 122 a 172 b 222 d
23 a 73 b 123 b 173 a 223 d
24 a 74 d 124 b 174 c 224 a
25 b 75 d 125 b 175 b 225 d
26 a 76 b 126 c 176 a&d 226 c
27 c 77 b 127 b 177 c 227 a
28 b 78 a 128 a 178 b 228 b
29 a 79 c 129 c 179 e 229 b
30 c 80 b 130 b 180 f 230 d
31 b 81 a 131 b 181 d 231 c
32 c 82 a 132 a 182 e 232 c
33 d 83 c 133 c 183 d 233 a
34 a 84 d 134 c 184 b 234 b
35 b 85 d 135 b 185 e 235 b
36 a 86 a 136 d 186 c 236 a
37 b 87 c 137 a 187 b 237 b
38 b 88 a 138 b 188 b 238 d
39 c 89 a 139 b 189 b 239 b
40 a 90 b 140 a 190 a 240 b
41 b 91 b 141 a 191 c 241 b
42 d 92 a 142 c 192 a 242 a
43 b 93 a 143 a 193 c 243 c
44 a 94 b 144 b 194 b 244 c
45 d 95 a 145 a 195 c 245 a
46 c 96 d 146 a 196 c 246 d
47 d 97 a 147 b 197 b 247 b
48 c 98 b 148 b 198 b 248 d
49 c 99 c 149 b 199 c 249 b
50 c 100 d 150 c 200 b 250 a
CHAPTER 6
Sequence-String
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.
Multiple choice questions
1. What is the correct way to create a string in Python?
a. string = ‘Hello, World!’
b. string = “Hello, World!”
c. string = ‘’’Hello, World!’’’
d. All of the above
2. Which of the following is an immutable data type in Python?
a. List
b. Tuple
c. String
d. Dictionary
3. Which method is used to find the length of a string in Python?
a. len() c. count()
b. length() d. size()
4. What will be the output of the following code:
text = "Python"
print(text[2:4])
a. Py c. to
b. th d. thon
5. Which method is used to convert a string to lowercase in Python?
a. tolower() c. lowercase()
b. lower() d. smallcase()
6. What is the result of the expression "Hello" + "World" in
Python?
a. “Hello World” c. “Hello World”
b. “HelloWorld” d. “Hello + World”
7. How do you check if a string contains a specific substring in
Python?
a. Using the substr() function
b. Using the in keyword
c. Using the contains() method
d. Using the substring() function
8. Which method is used to split a string into a list of substrings
using a specified delimiter?
a. split() c. separate()
b. divide() d. splitstring()
9. Which of the following methods is used to remove leading and
trailing whitespaces from a string?
a. strip() c. clean()
b. trim() d. clear()
10. What will the str.upper() method do in Python?
a. Convert the string to uppercase
b. Convert the string to lowercase
c. Remove all spaces from the string
d. Count the number of uppercase letters in the string
11. Which of the following methods is used to replace a substring in a
string with another substring?
a. replace() c. swap()
b. substitute() d. switch()
12. What is the result of the expression "Hello,
World!".split(",")?
a. [‘Hello, World!’]
b. [‘Hello’, ‘ World!’]
c. [‘Hello’, ‘World!’]
d. [‘Hello, ‘, ‘World!’]
13. In Python, which operator is used to concatenate two or more
strings?
a. + c. *
b. & d. %
14. What does the str.startswith(prefix) method in Python
return?
a. True if the string starts with the specified prefix, otherwise false
b. The index where the prefix starts in the string
c. The number of occurrences of the prefix in the string
d. The substring of the string that starts with the prefix
15. Which method is used to check if all characters in a string are
alphabetic in Python?
a. isalphabet() c. isalphabetic()
b. isalpha() d. alpha()
16. What will be the output of the code: len("Hello")?
a. 6 c. 4
b. 5 d. 3
17. How can you reverse a string in Python?
a. Using the str.reverse() method
b. Using slicing: string[::-1]
c. Using a loop
d. Python does not support string reversal
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.
24. What is the result of the expression "abc def".split() in
Python?
a. [‘abc’, ‘def’]
b. [‘abc def’]
c. [‘abc’, ‘ ‘, ‘def’]
d. [‘abcdef’]
25. Which of the following methods can be used to check if a string
contains only digits (0-9)?
a. isnumber() c. isnumeric()
b. isdigit() d. isint()
26. What is the output of the code “Hello”.center(10, ‘-’)?
a. “Hello-----” c. “--Hello---”
b. “-----Hello” d. “Hello--”
27. Which method is used to capitalize the first character of a string in
Python?
a. uppercase() c. capitalize()
b. firstupper() d. firstletter()
28. In Python, which method is used to check if a string ends with a
specified suffix?
a. endswith()
b. ends()
c. suffixed()
29. What is the result of the expression "apple" < "banana" in
Python?
a. True c. None
b. False d. It will raise an error.
30. How do you convert a string to a list of characters in Python?
a. Using the split() method
b. Using the list() constructor
c. Using the join() method
d. Strings cannot be converted to lists in Python.
31. What is the result of the code "Hello,
World!".replace("World", "Python")?
a. “Hello, Python!”
b. “Hello, WorldPython!”
c. “Hello, PythonPython!”
d. “Hello, Python World!”
32. How can you check if a string is entirely composed of alphabetic
characters (letters) in Python?
a. Using the isalpha() method
b. Using the isletter() method
c. Using the isalphabetic() method
d. There is no built-in method for this in Python.
33. What is the result of the expression "Python"[1:4]?
a. “Pyt” c. “tho”
b. “yth” d. “thon”
34. Which method is used to check if a string is empty in Python?
a. isempty()
b. isnull()
c. is_empty()
35. What is the result of the expression str(123) in Python?
a. “123” c. ‘123’
b. 123 d. [123]
36. Which method is used to check if a string contains only whitespace
characters in Python?
a. isspace() b. iswhitespace()
c. whitespace() d. containspace()
37. What is the result of the expression "Python"[-3:] in Python?
a. “Pyt” c. “hon”
b. “tho” d. “thon”
38. Which of the following methods can be used to convert a string to
title case (capitalize the first letter of each word)?
a. title() c. capitalize()
b. uppercase() d. to_title()
39. What is the output of the code "Hello,
World!".index("W")?
a. 6 c. 8
b. 7 d. 9
40. Which of the following methods is used to check if a string
contains only alphanumeric characters (letters and digits) in
Python?
a. isalpha() c. isalphanumeric()
b. isalnum() d. isnumeric()
41. What is the result of the expression "Python"[::-1] in
Python?
a. “Python”
b. “nohtyP”
c. “”
d. It will raise an error.
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
43. Which of the following is a valid way to create a multiline string in
Python?
a. multiline = “Line 1\nLine 2\nLine 3”
b. multiline = “Line 1, Line 2, Line 3”
c. multiline = ‘Line 1, Line 2, Line 3’
d. multiline = “Line 1; Line 2; Line 3”
44. What is the output of the code "Hello".isupper()?
a. True c. None
b. False d. It will raise an error.
45. Which method is used to swap the case of characters in a string in
Python (e.g., uppercase to lowercase and vice versa)?
a. switchcase() c. changecase()
b. swapcase() d. casechange()
46. What will the str.find(substring) method return if the
substring is not found in the string?
a. -1
b. 0
c. None
d. An error
47. What is the result of the code "Python".islower()?
a. True c. None
b. False d. It will raise an error.
48. Which method is used to check if a string is a valid identifier
(variable name) in Python?
a. isidentifier() c. valididentifier()
b. isvariable() d. checkvariable()
49. What does the str.join(iterable) method do in Python?
a. Splits the string into substrings
b. Joins the elements of an iterable into a single string using the
string as a separator
c. Reverses the string
d. Counts the occurrences of a substring
50. What is the output of the code "python".replace("p",
"P", 1)?
a. “Python” c. “python”
b. “Pythton” d. “Ppython”
51. How can you check if a string contains only lowercase letters in
Python?
a. Using the islower() method
b. Using the islowercase() method
c. Using the lowercase() method
d. There is no built-in method for this in Python.
52. What is the result of the expression "Python"[1:-1] in
Python?
a. “P” c. “ytho”
b. “Pytho” d. “ython”
53. Which method is used to check if a string contains only printable
characters (excluding control characters and special whitespace)
in Python?
a. isprintable() c. isprint()
b. isvisible() d. isvalid()
54. What is the output of the code " Python ".strip()?
a. “Python” c. “Python “
b. “ Python” d. “ Python “
55. In Python, how can you check if a string contains a specific
character or substring, and get its index or position?
a. Using the locate() method
b. Using the search() method
c. Using the find() method
d. Using the index() method
56. What is the output of the code "Python".count("o")?
a. 0 c. 2
b. 1 d. 3
57. Which of the following methods is used to convert a string to
lowercase while making changes in the original string?
a. tolower()
b. lower()
c. lowercase()
d. smallcase()
58. What will be the output of the code str(3.14)?
a. “3.14” c. ‘3.14’
b. 3.14 d. [3.14]
59. What is the output of the code "Hello, World!".split("
")?
a. [‘Hello, World!’]
b. [‘Hello’, ‘World!’]
c. [‘Hello’, ‘ World!’]
d. [‘Hello,’, ‘World!’]
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.
61. What is the result of the code "apple".isnumeric()?
a. True
b. False
c. None
d. It will raise an error.
62. Which of the following methods is used to repeat a string a
specified number of times in Python?
a. repeat()
b. duplication()
c. replicate()
d. (Multiplication operator)
63. What is the output of the code 0*?
a. True c. None
b. False d. It will raise an error.
64. How can you remove leading and trailing characters other than
spaces from a string in Python?
a. Using the remove() method
b. Using the trim() method
c. Using the lstrip() and rstrip() methods
d. Using the clear() method
65. What is the output of the code "python".isidentifier()?
a. True c. None
b. False d. It will raise an error.
66. How can you check if a string contains only printable characters
and does not include control characters in Python?
a. Using the isvisible() method
b. Using the isvalid() method
c. Using the isprintable() method
d. Using the isprint() method
67. What is the result of the expression "Python"[2:6:2] in
Python?
a. “Ph” c. “yt”
b. “to” d. “n”
68. Which method is used to replace the first occurrence of a
substring with another substring in a string in Python?
a. replace_first() c. replace()
b. replace_once() d. substitute()
69. What is the output of the code "Hello,
World!".isalpha()?
a. True c. None
b. False d. It will raise an error.
70. How can you check if a string contains only decimal characters (0-
9) in Python?
a. Using the isdecimal() method
b. Using the isnumeric() method
c. Using the isdigit() method
d. Using the isint() method
71. What is the result of the expression "Python"[1:5:2] in
Python?
a. “P” c. “yt”
b. “to” d. “n”
72. Which method is used to check if a string contains only valid
Python identifiers in Python?
a. isvalididentifier()
b. isidentifier()
c. isvariable()
d. isname()
73. What is the output of the code "Python".endswith("py")?
a. True c. None
b. False d. It will raise an error.
74. How do you check if a string contains a specific substring, and get
the index of its first occurrence in Python?
a. Using the locate() method
b. Using the search() method
c. Using the find() method
d. Using the index() method
75. What is the output of the code "Python".count("P")?
a. 0 c. 2
b. 1 d. 3
76. What is the result of the code "Hello,
World!".rfind("o")?
a. 5 c. 7
b. 6 d. 8
77. Which method is used to remove whitespace characters from both
ends of a string in Python?
a. trim() c. strip()
b. clear() d. remove()
78. What is the output of the code "Hello,
World!".lstrip("Hello, ")?
a. “World!” c. “ello, World!”
b. “Hello, World!” d. “Hello, World! “
79. In Python, how can you check if a string contains only decimal
characters (0-9) and does not include any other characters?
a. Using the isnumber() method
b. Using the isdigit() method
c. Using the isdecimal() method
d. Using the isnumeric() method
80. What is the result of the code "Python".isprintable()?
a. True c. None
b. False d. It will raise an error.
81. Which method is used to check if a string is entirely composed of
ASCII characters in Python?
a. isascii() c. validascii()
b. ascii() d. containsascii()
82. What is the output of the code "python".isalpha()?
a. True c. None
b. False d. It will raise an error.
83. How do you check if a string contains only digits (0-9) and does
not include any other characters in Python?
a. Using the isnumber() method
b. Using the isdigit() method
c. Using the isdecimal() method
d. Using the isnumeric() method
84. What is the result of the code "Python".index("P")?
a. 0 c. 2
b. 1 d. 3
85. How can you replace all occurrences of a substring in a string with
another substring in Python?
a. Using the replace_all() method
b. Using a loop
c. Using the replace() method with no limit argument
d. Using the str.replaceAll() method
86. What is the output of the code "Python".isidentifier()?
a. True c. None
b. False d. It will raise an error.
87. How can you check if a string contains only uppercase letters (A-
Z) and does not include any other characters in Python?
a. Using the isupper() method
b. Using the isuppercase() method
c. Using the upper() method
d. Using the isuppercaseletter() method
88. What is the output of the code "Python".count("p")?
a. 0 c. 2
b. 1 d. 3
89. How can you check if a string contains only lowercase letters (a-z)
and does not include any other characters in Python?
a. Using the islowercase() method
b. Using the islower() method
c. Using the lower() method
d. Using the islowerletter() method
90. What is the result of the code "Python".isnumeric()?
a. True c. None
b. False d. It will raise an error.
91. Which method is used to check if a string contains only valid
Python variable names in Python?
a. isvalididentifier()
b. isvariable()
c. isidentifier()
d. isname()
92. What is the output of the code "Python".startswith("P")?
a. True
b. False
c. None
d. It will raise an error.
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
94. What is the output of the code "Python".endswith("n")?
a. True c. None
b. False d. It will raise an error.
95. In Python, how can you check if a string contains only valid
Python identifiers and does not include any other characters?
a. Using the isidentifier() method
b. Using the isvalididentifier() method
c. Using the isvariable() method
d. Using the isname() method
96. What is the result of the code "Hello,
World!".rfind("z")?
a. -1
b. 0
c. None
d. It will raise an error.
97. Which method is used to remove leading whitespace characters
from a string in Python?
a. trim() c. lstrip()
b. clear() d. remove()
98. What is the output of the code " Python ".rstrip()?
a. “ Python” c. “ Python “
b. “Python “ d. “Python”
99. How can you check if a string contains only valid Python variable
names and does not include any other characters in Python?
a. Using the isvalididentifier() method
b. Using the isvariable() method
c. Using the isname() method
d. Using the isvalidvar() method
100. How can you check if a string is entirely composed of whitespace
characters in Python?
a. Using the iswhitespace() method
b. Using the isspace() method
c. Using the isblank() method
d. Using the isempty() method
101. What is the result of the code "Python".count("Z")?
a. 0 c. 2
b. 1 d. 3
102. Which method is used to check if a string contains only printable
characters (including spaces) in Python?
a. isprintable() c. isvalid()
b. isvisible() d. isprint()
103. What is the output of the code "Python".replace("n",
"N")?
a. “Python” c. “Pytho”
b. “PythoN” d. “PythoNN”
104. How do you check if a string contains only lowercase letters (a-z)
and digits (0-9) in Python?
a. Using the islower() method
b. Using the isalpha() method
c. Using the isalnum() method
d. Using the islowercase() method
105. What is the output of the code "Hello,
World!".splitlines()?
a. [‘Hello, World!’]
b. [‘Hello,’, ‘World!’]
c. [‘Hello, World!’]
d. [‘Hello,’, ‘ World!’]
106. Which method is used to convert a string to a list of lines (split by
newline characters) in Python?
a. splitlines()
b. split(‘\n’)
c. lines()
d. listlines()
107. What is the result of the code " ".isspace()?
a. True
b. False
c. None
d. It will raise an error.
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
109. What is the output of the code "Python".isprintable()?
a. True
b. False
c. None
d. It will raise an error.
110. How do you check if a string is composed of only uppercase letters
(A-Z) and digits (0-9) in Python?
a. Using the isupper() method
b. Using the isalnum() method
c. Using the isuppercase() method
d. Using the isuppercaseletter() method
111. What is the result of the code "Python".split(None)?
a. [‘Python’]
b. [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
c. [‘Python’, ‘’]
d. [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘’]
112. Which method is used to check if a string contains only valid
Python variable names (identifiers) and does not include any other
characters in Python?
a. isvalididentifier()
b. isvariable()
c. isname()
d. isvalidvar()
113. What is the output of the code "Python".rjust(10)?
a. “Python” c. “ Python “
b. “ Python “ d. “ Python”
114. How can you check if a string contains only lowercase letters (a-z)
and does not include any other characters in Python?
a. Using the islowercase() method
b. Using the islower() method
c. Using the lower() method
d. Using the islowerletter() method
115. What is the output of the code "Hello, World!".ljust(20,
"*")?
a. “****Hello, World!*******”
b. “Hello, World!”
c. “*****Hello, World!”
d. “Hello, World!********”
116. Which method is used to check if a string contains only
hexadecimal characters (0-9, a-f, A-F) in Python?
a. ishex()
b. ishexadecimal()
c. ishexdigits()
117. What is the result of the code "Python".zfill(10)?
a. “Python0000” c. “Python”
b. “0000Python” d. “00000Python”
118. How do you check if a string contains only uppercase letters (A-Z)
and does not include any other characters in Python?
a. Using the isupper() method
b. Using the isuppercase() method
c. Using the upper() method
d. Using the isuppercaseletter() method
119. What is the output of the code "Python".zfill(5)?
a. “Python”
b. “0Python”
c. “000Python”
d. “Python0”
120. What is the result of the code "Python".isnumeric()?
a. True
b. False
c. None
d. It will raise an error.
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
122. What is the output of the code "Python".rstrip("n")?
a. “Pytho” c. “Pytho”
b. “Python” d. “Pytho “
123. Which method is used to count the number of non-overlapping
occurrences of a substring in a string in Python?
a. count() c. index()
b. find() d. len()
124. How can you check if a string is composed of only digits (0-9) and
underscores (_) in Python?
a. Using the isdigit() method
b. Using the isalnum() method
c. Using the isnumberunderscore() method
d. Using the isvalididentifier() method
125. What is the output of the code "Python".rstrip("z")?
a. “Python” c. “Pytho “
b. “Pytho” d. “Pythonz”
126. How can you check if a string is composed of only alphanumeric
characters (letters and digits) and underscores (_) in Python?
a. Using the isalnum() method
b. Using the isalpha() method
c. Using the isalphanumericunderscore() method
d. Using the isvalididentifier() method
127. What is the result of the code "Python".index("p")?
a. 0
b. 1
c. 2
d. 3
128. How can you check if a string is composed of only alphabetic
characters (letters) and underscores (_) in Python?
a. Using the isalpha() method
b. Using the isletter() method
c. Using the isalphabeticunderscore() method
d. Using the isvalididentifier() method
129. What is the output of the code "Python".startswith("p")?
a. True
b. False
c. None
d. It will raise an error.
130. Which method is used to check if a string contains only valid
Python variable names (identifiers) and does not include any other
characters in Python?
a. isvalididentifier()
b. isvariable()
c. isname()
d. isvalidvar()
131. What is the output of the code "Python".zfill(2)?
a. “Python”
b. “00Python”
c. “Python00”
d. “Python”
132. How can you check if a string is composed of only uppercase
letters (A-Z) and underscores (_) in Python?
a. Using the isupper() method
b. Using the isalpha() method
c. Using the isupperunderscore() method
d. Using the isvalididentifier() method
133. What is the result of the code "Hello, World!".rjust(20,
"-")?
a. “Hello, World!-------”
b. “-------Hello, World!”
c. “Hello, World!”
d. “Hello, World!--------”
134. How can you check if a string contains only alphanumeric
characters (letters and digits) and does not include any other
characters in Python?
a. Using the isalnum() method
b. Using the isalpha() method
c. Using the isalphanumeric() method
d. Using the isvalididentifier() method
135. What is the output of the code " Python,p ".strip()?
a. “ython” c. “pPython “
b. “ Python “ d. “ Python,p”
136. Which method is used to remove whitespace characters from both
ends of a string in Python?
a. trim() c. strip()
b. clear() d. remove()
137. What is the output of the code "Hello,
World!".split(None, 1)?
a. [‘Hello, World!’]
b. [‘Hello,’, ‘World!’]
c. [‘Hello, World!’]
d. [‘P’, ‘ython’]
138. How do you check if a string is composed of only decimal
characters (0-9) and underscores (_) in Python?
a. Using the isdecimal() method
b. Using the isdigit() method
c. Using the isnumberunderscore() method
d. Using the isvalididentifier() method
139. What is the result of the code "Python".rjust(6, "-")?
a. “ -Python” c. “Python---”
b. “---Python” d. “Python”
140. 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
141. What is the result of the code "Python".rsplit("o", 1)?
a. [‘Pyth’, ‘n’] c. [‘Python’]
b. [‘Pytho’, ‘’] d. [‘Pytho’, ‘n’]
142. Which method is used to check if a string contains only printable
characters (including spaces) and does not include control
characters in Python?
a. isprintable() c. isvalid()
b. isvisible() d. isprint()
143. What is the output of the code "Python".partition("t")?
a. (‘Py’, ‘t’, ‘hon’) c. (‘Python’, ‘t’, ‘on’)
b. (‘Python’, ‘’, ‘’) d. (‘P’, ‘ython’, ‘’)
144. How do you check if a string is composed of only digits (0-9) and
underscores (_) in Python?
a. Using the isdigit() method
b. Using the isalnum() method
c. Using the isnumberunderscore() method
d. Using the isvalididentifier() method
145. What is the result of the code "Python".rsplit("Z", 1)?
a. [‘Python’] c. [‘Pytho’, ‘n’]
b. [‘Pytho’, ‘’] d. [‘Pyth’, ‘on’]
146. How can you check if a string contains only alphanumeric
characters (letters and digits) and underscores (_) in Python?
a. Using the isalnum() method
b. Using the isalpha() method
c. Using the isalphanumericunderscore() method
d. Using the isvalididentifier() method
147. What is the output of the code "Python".rstrip("o")?
a. “Pyth” c. “Pytho”
b. “Python” d. “Pytho “
148. Which method is used to count the number of non-overlapping
occurrences of a substring in a string in Python?
a. count() c. index()
b. find() d. len()
149. How can you check if a string is composed of only uppercase
letters (A-Z) and underscores (_) in Python?
a. Using the isupper() method
b. Using the isalpha() method
c. Using the isupperunderscore() method
d. Using the isvalididentifier() method
150. What is the output of the code "Python".rstrip("Z")?
a. “Python” c. “Pythonz”
b. “Pytho” d. “Pytho “
151. How do you check if a string is composed of only alphabetic
characters (letters) and underscores (_) in Python?
a. Using the isalpha() method
b. Using the isletter() method
c. Using the isalphabeticunderscore() method
d. Using the isvalididentifier() method
152. What is the output of the code "Python".startswith("p")?
a. True
b. False
c. None
d. It will raise an error.
153. Which method is used to check if a string contains only valid
Python variable names (identifiers) and does not include any other
characters in Python?
a. isvalididentifier()
b. isvariable()
c. isname()
d. isvalidvar()
154. What is the result of the code "Python".zfill(5)?
a. “0Python0” c. “Python00”
b. “00Python” d. “Python”
155. How can you check if a string is composed of only uppercase
letters (A-Z) and digits (0-9) in Python?
a. Using the isupper() method
b. Using the isalnum() method
c. Using the isuppercase() method
d. Using the isuppercaseletter() method
156. What is the output of the code "Hello,
World!".strip(",")?
a. “Hello, World!”
b. “Hello, World”
c. “Hello, World”
d. “Hello, World! “
157. Which method is used to remove whitespace characters from both
ends of a string in Python?
a. trim() c. strip()
b. clear() d. remove()
158. What is the output of the code "Python".split(None, 1)?
a. [‘Python’] c. [‘Python’, ‘’]
b. [‘P’, ‘ython’] d. [‘Python’, ‘ython’]
159. How do you check if a string is composed of only decimal
characters (0-9) and underscores (_) in Python?
a. Using the isdecimal() method
b. Using the isdigit() method
c. Using the isnumberunderscore() method
d. Using the isvalididentifier() method
160. How can you check if a string is composed of only hexadecimal
characters (0-9, a-f, A-F) and underscores (_) in Python?
a. Using the ishex() method
b. Using the ishexadecimal() method
c. Using the ishexdigits() method
d. Using the ishexchars() method
161. What is the result of the code "Hello,
World!".rfind("z")?
a. -1 c. None
b. 0 d. It will raise an error.
162. How can you check if a string is composed of only valid Python
variable names and does not include any other characters in
Python?
a. Using the isidentifier() method
b. Using the isvalididentifier() method
c. Using the isvariable() method
d. Using the isname() method
163. What is the output of the code " Python ".rstrip()?
a. “ Python “
b. “ Python”
c. “Python “
d. “ Python “
164. Which method is used to remove leading whitespace characters
from a string in Python?
a. trim() c. lstrip()
b. clear() d. remove()
165. What is the output of the code "Hello,
World!".endswith("n")?
a. True c. None
b. False d. It will raise an error.
166. In Python, how can you check if a string contains only valid
Python identifiers and does not include any other characters?
a. Using the isvalididentifier() method
b. Using the isvalidvar() method
c. Using the isvariable() method
d. Using the isname() method
167. What is the result of the code "Python".isidentifier()?
a. True
b. False
c. None
d. It will raise an error.
168. How can you check if a string contains only uppercase letters (A-
Z) and does not include any other characters in Python?
a. Using the isupper() method
b. Using the isuppercase() method
c. Using the upper() method
d. Using the isuppercaseletter() method
169. What is the output of the code "Python".count("p")?
a. 0 c. 2
b. 1 d. 3
170. How can you check if a string contains only lowercase letters (a-z)
and does not include any other characters in Python?
a. Using the islowercase() method
b. Using the islower() method
c. Using the lower() method
d. Using the islowerletter() method
171. What is the result of "Hello, " + "World!" in Python?
a. “Hello, World!”
b. “Hello, World!”
c. “Hello, +, World!”
d. Error
172. How do you find the length of a string in Python?
a. str.size() c. length(str)
b. len(str) d. str.length()
173. Which of the following methods is used to convert a string to
lowercase in Python?
a. str.lower()
b. str.toLower()
c. str.LowerCase()
d. str.convertLower()
174. Which method is used to split a string into a list of substrings
based on a delimiter?
a. split()
b. break()
c. separate()
d. explode()
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
176. What is the index of the first character in a string?
a. 0 c. -1
b. 1 d. 2
177. What does string[2:5] represent in Python?
a. The 2nd character of the string
b. A new string starting from the 2nd character and ending before
the 5th character
c. The 5th character of the string
d. An error
178. What does string[:-3] represent in Python?
a. The last 3 characters of the string
b. A new string without the last 3 characters
c. The first 3 characters of the string
d. An error
179. How can you reverse a string using slicing in Python?
a. string[::-1]
b. string.reverse()
c. string.reverseSlice()
d. string.reverse(-1)
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()
184. Which method is used to check if a string starts with a specific
prefix?
a. starts()
b. startswith()
c. begin()
d. startswithwith()
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.
187. Which of the following method is used to check if all characters in
a string are alphanumeric (letters or numbers)?
a. isalphanum() c. isnumeric()
b. isalpha() d. isalnum()
188. Which of the following method can be used to capitalize the first
character of each word in a string?
a. upper() c. title()
b. capitalize() d. initialCap()
189. Which of the following is used for string interpolation in Python?
a. sprintf() c. interpolate()
b. format() d. insert()
190. What does f-string stand for in Python?
a. Formatted string
b. Function string
c. Fast string
d. None of the above
191. What is the correct way to format a string using f-strings?
a. f”Hello, {name}!”
b. “Hello, {name}!”.format()
c. “Hello, {name}!” % (name)
d. format(“Hello, {}!”, name)
192. Which function can be used to left-align a string within a specific
width?
a. left_align() c. align_left()
b. ljust() d. left()
193. What is the purpose of the % operator in string formatting?
a. It is used for placeholder substitution.
b. It’s used for concatenating strings.
c. It’s used to access string methods.
d. It is used for division.
194. Which escape sequence is used for a newline character in Python?
a. \n c. \t
b. \r d. \b
195. How can you include a single quote within a single-quoted string?
a. Use double quotes around the string.
b. Use a backslash before the single quote: \’
c. It’s not possible.
d. Use two single quotes: ‘’
196. What does \\ represent in a string?
a. It is a backslash character.
b. It is a tab character.
c. It is an escape sequence for a single quote.
d. It is an error.
197. Which escape sequence is used for a tab character in Python?
a. \n c. \t
b. \r d. \b
198. How do you compare two strings for equality in Python?
a. Using the == operator
b. Using the = operator
c. Using the compare() method
d. Using the is_equal() function
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()
200. Which of the following comparisons is case-sensitive?
a. str1 == str2
b. str1.equals(str2)
c. str1.equalsIgnoreCase(str2)
d. All of the above
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.
206. Which method returns the index of the last occurrence of a
substring in a string, or -1 if not found?
a. find() c. rfind()
b. index() d. rindex()
207. How can you check if a string contains a specific substring in
Python?
a. Using the search() method
b. Using the contains() method
c. Using the in keyword
d. Using the find() method
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)
211. What does string.index("Python") do if “Python” is not
present in string?
a. Returns -1
b. Returns None
c. Raises a ValueError
d. Returns 0
212. Which method can be used to remove whitespace characters from
both ends of a string, but not within the string?
a. strip()
b. lstrip()
c. rstrip()
d. remove_whitespace()
213. How can you convert a string to uppercase in Python?
a. string.toUppercase()
b. string.upper()
c. string.makeUpperCase()
d. string.toUpperCase()
214. Which method can be used to replace a specified number of
occurrences of a substring in a string?
a. replace()
b. substitute()
c. replace_all()
d. replace_count()
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
216. What does the splitlines() method do in Python?
a. Splits a string into a list based on line breaks.
b. Splits a string into a list based on spaces.
c. Splits a string into individual characters.
d. Removes all whitespace from a string.
217. What is the purpose of the .format() method in Python string
formatting?
a. It is used to insert values into a string.
b. It is used to format dates.
c. It is used to create a new string.
d. It is used to remove spaces.
218. Which of the following is a correct way to format a string using
.format()?
a. “Hello, {}!”.format(name)
b. “Hello, {name}!”.format()
c. format(“Hello, {}!”, name)
d. format(“Hello, {name}!”)
219. How can you specify the position of arguments in a formatted
string using .format()?
a. By using numerical indices.
b. By using the & character.
c. By enclosing the arguments in square brackets.
d. You can’t specify positions.
220. Which of the following is used for string interpolation in Python?
a. .interpolate()
b. .format()
c. .replace()
d. .insert()
221. What does an f-string allow you to do in Python?
a. Embed expressions and variables in string literals.
b. Format a string without any placeholders.
c. Define a function that returns a string.
d. Concatenate two strings.
222. What does the escape sequence \t represent in a string?
a. A tab character
b. A newline character
c. A backspace character
d. A null character
223. How can you include a double quote within a double-quoted
string?
a. Use a backslash before the double quote: \”
b. Use single quotes: ‘’
c. It’s not possible.
d. Use two double quotes: “”
224. What does \\ represent in a string?
a. A backslash character
b. An escape sequence for a single quote
c. A tab character
d. A space character
225. What is the escape sequence for a newline character in Python?
a. \n c. \t
b. \r d. \b
226. What does the escape sequence \\n represent in a string?
a. A newline character
b. A tab character
c. A backslash followed by the letter “n”
d. A space character
227. Which method can be used to compare two strings in a case-
insensitive manner?
a. equals()
b. compare_ignore_case()
c. case_insensitive_equals()
d. compare()
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()
230. What is the result of the expression "apple" == "Apple"?
a. True
b. False
c. None
d. An error
231. How can you remove all whitespace characters from a string in
Python?
a. trim()
b. strip()
c. remove_whitespace()
d. delete_whitespace()
232. Which method can be used to extract a substring from a string by
specifying its start and end positions?
a. substring() c. splice()
b. slice() d. substr()
233. What method can be used to check if a string contains only
alphabetic characters (letters)?
a. isalpha() b. isalphabet()
c. isletters() d. isalphastring()
234. How can you convert a string to title case (capitalize the first letter
of each word)?
a. titlecase() c. title()
b. to_title() d. capitalize()
235. Which method can be used to remove all non-alphanumeric
characters from a string?
a. strip()
b. remove_non_alnum()
c. isalpha()
d. isalnum()
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)
239. What does string.index("Python") do if “Python” is not
present in string?
a. Returns -1
b. Returns None
c. Raises a ValueError
d. Returns 0
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
241. What method can be used to remove whitespace characters from
the beginning of a string?
a. strip()
b. lstrip()
c. rstrip()
d. remove_whitespace()
242. How can you convert a string to lowercase in Python?
a. string.toLower()
b. string.lower()
c. string.makeLower()
d. string.to_lowercase()
243. Which method can be used to replace a specified number of
occurrences of a substring in a string?
a. replace()
b. substitute()
c. replace_all()
d. replace_count()
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
245. What does the splitlines() method do in Python?
a. Splits a string into a list based on line breaks.
b. Splits a string into a list based on spaces.
c. Splits a string into individual characters.
d. Removes all whitespace from a string.
246. What is the purpose of the .format() method in Python string
formatting?
a. It’s used to insert values into a string.
b. It’s used to format dates.
c. It’s used to create a new string.
d. It’s used to remove spaces.
247. Which of the following is a correct way to format a string using
.format()?
a. “Hello, {}!”.format(name)
b. “Hello, {name}!”.format()
c. format(“Hello, {}!”, name)
d. format(“Hello, {name}!”)
248. How can you specify the position of arguments in a formatted
string using .format()?
a. By using numerical indices.
b. By using the and character.
c. By enclosing the arguments in square brackets.
d. You cannot specify positions.
249. Which of the following is used for string interpolation in Python?
a. .interpolate()
b. .format()
c. .replace()
d. .insert()
250. What does an f-string allow you to do in Python?
a. Embed expressions and variables in string literals.
b. Format a string without any placeholders.
c. Define a function that returns a string.
d. Concatenate two strings.
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 d 51 a 101 a 151 a 201 c
2 c 52 b 102 a 152 b 202 b
3 a 53 a 103 b 153 a 203 c
4 b 54 a 104 c 154 d 204 c
5 b 55 c 105 a 155 d 205 a
6 a 56 c 106 a 156 a 206 c
7 b 57 b 107 a 157 c 207 c
8 a 58 a 108 a 158 a 208 c
9 a 59 b 109 a 159 c 209 b
10 a 60 b 110 b 160 a 210 a
11 a 61 b 111 a 161 a 211 c
12 b 62 d 112 a 162 a 212 a
13 a 63 a 113 d 163 b 213 b
14 a 64 c 114 b 164 c 214 a
15 b 65 a 115 d 165 b 215 a
16 b 66 c 116 a 166 a 216 a
17 b 67 b 117 b 167 a 217 a
18 b 68 c 118 a 168 a 218 a
19 b 69 b 119 a 169 a 219 a
20 a 70 a 120 b 170 b 220 b
21 c 71 b 121 d 171 a 221 a
22 b 72 b 122 a 172 b 222 a
23 d 73 b 123 a 173 a 223 a
24 a 74 c 124 a 174 a 224 a
25 b 75 b 125 a 175 a 225 a
25 b 75 b 125 a 175 a 225 a
26 a 76 d 126 c 176 a 226 c
27 c 77 c 127 a 177 b 227 b
28 a 78 a 128 d 178 b 228 b
29 a 79 c 129 b 179 a 229 d
30 b 80 a 130 a 180 b 230 b
31 a 81 a 131 d 181 a 231 b
32 a 82 a 132 c 182 b 232 b
33 a 83 b 133 b 183 a 233 a
34 d 84 a 134 a 184 b 234 c
35 a 85 c 135 d 185 b 235 b
36 a 86 a 136 c 186 a 236 c
37 c 87 a 137 b 187 d 237 b
38 a 88 b 138 d 188 c 238 a
39 b 89 b 139 d 189 b 239 c
40 b 90 b 140 c 190 a 240 b
41 b 91 c 141 a 191 a 241 b
42 b 92 a 142 a 192 b 242 b
43 a 93 c 143 a 193 a 243 a
44 b 94 a 144 c 194 a 244 a
45 b 95 b 145 a 195 b 245 a
46 a 96 a 146 c 196 a 246 a
47 b 97 c 147 b 197 c 247 a
48 a 98 a 148 a 198 a 248 a
49 b 99 a 149 c 199 b 249 b
50 a 100 b 150 a 200 a 250 a
CHAPTER 7
Lists
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
2. How do you declare an empty list in Python?
a. list = [] c. list = ()
b. list = {} d. list = [None]
3. Which of the following methods is used to add an element to the
end of a list in Python?
a. list.add(element)
b. list.append(element)
c. list.insert(element)
d. list.extend(element)
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
7. Which of the following is true about lists in Python?
a. Lists are immutable
b. Lists can only store elements of the same data type
c. Lists can contain a mixture of data types
d. Lists are limited to a fixed size
8. What is the correct way to get the length (number of elements) of a
list in Python?
a. len(list)
b. list.length()
c. list.size()
d. length(list)
9. In Python, how are lists indexed?
a. Lists use zero-based indexing
b. Lists use one-based indexing
c. Lists use negative indexing only
d. Lists use floating-point indexing
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
11. How do you check if a list is empty?
a. if list.is_empty():
b. if list.empty():
c. if not list:
d. if list.size == 0:
12. Which of the following method is used to check if a list is in
ascending order?
a. list.is_ordered()
b. isAscending(list)
c. all(x < y for x, y in zip(list, list[1:]))
d. list.sort()
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
14. How can you check if a list is in descending order?
a. list.is_descending()
b. all(x > y for x, y in zip(list, list[1:]))
c. descend(list)
d. list.reverse()
15. What is the purpose of the reverse() method when applied to a
list?
a. Reverses the order of elements in the list
b. Sorts the list in descending order
c. Removes all occurrences of a specified element
d. Adds an element to the end of the list
16. What is the significance of the key parameter in the sorted()
function?
a. It specifies whether to sort in ascending or descending order
b. It is not used in sorting lists
c. It defines a custom function to determine the sort order
d. It is used to set the size of the sorted list
17. How is the indexing of lists done?
a. One-based indexing
b. Zero-based indexing
c. Negative indexing only
d. Floating-point indexing
18. What does list[-1] represent when indexing a list?
a. The first element of the list
b. The last element of the list
c. An error because negative indexing is not allowed
d. The element at index 1
19. How can you access a sublist (slice) of a list?
a. list(sublist)
b. list[start:end]
c. list.slice(start, end)
d. sublist(list)
20. What is the result of list[2:5] when applied to a list?
a. The sublist containing elements at index 2, 3, and 4
b. The sublist containing elements at index 2, 3, 4, and 5
c. An error, because the end index cannot be greater than the length
of the list
d. The element at index 2 and 5
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
22. Which method is used to split a string into a list of substrings
based on a specified delimiter?
a. str.slice(delimiter)
b. str.split(delimiter)
c. str.divide(delimiter)
d. str.extract(delimiter)
23. What is the default delimiter used by the split() method?
a. Comma (,)
b. Space ( )
c. Underscore (_)
d. Tab (\t)
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)
26. What is the result of str.split() if the string contains
consecutive delimiters?
a. An empty string is added to the list for each consecutive delimiter
b. Consecutive delimiters are automatically removed from the string
c. An error is raised
d. Consecutive delimiters are treated as a single delimiter
27. How do you change the value of an element at a specific index in a
list?
a. list.set(index, value)
b. list.change(index, value)
c. list[index] = value
d. list.update(index, value)
28. Which method is used to add multiple elements to a list?
a. list.add_elements(new_elements)
b. list.append_multiple(new_elements)
c. list.extend(new_elements)
d. list.add(new_elements)
29. What happens if you try to update the value of an element at an
index that is beyond the length of the list?
a. An error is raised
b. The list is automatically extended to accommodate the new index
c. The value is updated, and the list is padded with None values
d. The list remains unchanged
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)
31. What does the += operator do when used with a list?
a. Concatenates the list with another list
b. Appends a new element to the end of the list
c. Updates the value of the first element in the list
d. Raises an error, as += is not supported for lists
32. How do you concatenate two lists?
a. list.combine(other_list)
b. list.add(other_list)
c. list.extend(other_list)
d. list.concatenate(other_list)
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
34. How can you concatenate a list with itself?
a. list.add(list)
b. list.concatenate(list)
c. list + list
d. list.extend(list)
35. What is the difference between using extend() and append()
for list concatenation?
a. There is no difference, and both can be used interchangeably
b. extend() adds a single element, while append() concatenates lists
c. append() adds a single element, while extend() concatenates lists
d. append() is used for strings, and extend() is used for numbers
36. If you have three lists: list1, list2, and list3, what is the correct way
to concatenate them into a single list?
a. list1 + list2 + list3
b. list1.concatenate(list2, list3)
c. list1.extend(list2).extend(list3)
d. list1.add(list2, list3)
37. Which of the following methods is used for iterating through
elements in a list?
a. for i in range(len(list))
b. for element in list:
c. while list.hasNext():
d. iterate(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
42. How do you check if an element is present in a list?
a. element.exists(list)
b. list.contains(element)
c. element in list
d. list.has(element)
43. What does the expression not element in list check?
a. Checks if the element is present in the list
b. Checks if the element is not present in the list
c. Checks if the list is empty
d. Checks if the element is None
44. What is the purpose of the index() method when applied to a
list?
a. Returns the index of the first occurrence of a specified element
b. Returns the last index of a specified element
c. Checks if an element exists in the list
d. Adds an element to the end of the list
45. Which of the following expressions checks if all elements in list1
are present in list2?
a. all(element in list1 for element in list2)
b. list1.contains_all(list2)
c. list1 in list2
d. list2.has_all(list1)
46. What is the result of list.count(element)?
a. Returns the total count of elements in the list
b. Returns the number of occurrences of a specified element in the
list
c. Checks if the list contains the specified element
d. Adds the specified element to the end of the list
47. What does the append() method do when applied to a list?
a. Adds a new list to the existing list
b. Adds a specified element to the end of the list
c. Removes the last element of the list
d. Appends a list to another list
48. Which function is used to find the average of elements in a list?
a. average(list)
b. mean(list)
c. avg(list)
d. sum(list) / len(list)
49. What does the index() method return?
a. Returns the first index of a specified element
b. Returns the last index of a specified element
c. Returns the total count of elements in the list
d. Returns the sum of all elements in the list
50. What is the purpose of the clear() method when applied to a
list?
a. Deletes the entire list
b. Removes the last element of the list
c. Clears all occurrences of a specified element
d. Deletes the first element of the list
51. Which function is used to find the count of a specified element in a
list?
a. count(list, element)
b. element.count(list)
c. list.count(element)
d. number_of_elements(list, element)
52. What does the reverse() method do when applied to a list?
a. Sorts the list in ascending order
b. Reverses the order of elements in the list
c. Removes the last element of the list
d. Creates a reversed copy of the list
53. How can you check if all elements in a list are True?
a. all_elements_true(list)
b. list.all()
c. all(list)
d. list.are_true()
54. What does the copy() method do when applied to a list?
a. Creates a shallow copy of the list
b. Creates a deep copy of the list
c. Copies the first half of the list
d. Copies the last element of the list
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)
57. What is the purpose of the insert() method when applied to a
list?
a. Adds a new list to the existing list
b. Inserts a specified element at a specified position in the list
c. Inserts a list into another list
d. Adds a specified element to the end of the list
58. Which function is used to check if any element in a list is True?
a. any_elements_true(list)
b. list.any()
c. any(list)
d. list.contains_true()
59. What does the remove() method do when applied to a list?
a. Removes the last element of the list
b. Removes a specified element from the list
c. Deletes the entire list
d. Deletes the first element of the 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()
61. What does the pop() method return?
a. Returns the last element of the list
b. Returns a specified element from the list
c. Returns the entire list
d. Returns the index of the popped element
62. What is the purpose of the extend() method when applied to a
list?
a. Adds a new list to the existing list
b. Extends the length of the list by a specified number
c. Adds a specified element to the end of the list
d. Adds multiple elements to the end of the list
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)
64. How can you check if any element in a list is False?
a. any_elements_false(list)
b. list.none()
c. none(list)
d. not any(list)
65. What is the result of applying the clear() method to an empty
list?
a. Deletes the entire list
b. Raises an error, as clear() cannot be applied to an empty list
c. Clears all occurrences of a specified element
d. Leaves the list unchanged
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
67. What does the following code snippet do?
def square_numbers(numbers):
return [num ** 2 for num in numbers]
result = square_numbers([1, 2, 3, 4])
print(result)
a. Prints the sum of squared numbers
b. Prints the square root of each number
c. Prints a list of squared numbers
d. Raises each number to the power of 2 and prints the result
68. What is the purpose of the following function?
def find_even(numbers):
return [num for num in numbers if num % 2
== 0]
a. Finds the sum of even numbers in the list
b. Returns a list of even numbers
c. Checks if all numbers in the list are even
d. Counts the number of even elements in the list
69. What will be the output of the following code?
def add_numbers(a, b):
return a + b
result = add_numbers(5, 7)
print(result)
a. 12
b. 57
c. 5 + 7
d. add_numbers(5, 7)
70. What does the following code accomplish?
def remove_duplicates(my_list):
return list(set(my_list))
a. Removes all elements from the list
b. Removes only the first occurrence of each element
c. Removes duplicates from the list
d. Creates a new list with reversed elements
71. What is the purpose of the return statement in a function?
a. Terminates the function and returns control to the calling code
b. Prints the output of the function to the console
c. Returns a value from the function to the calling code
d. Indicates the start of the function block
72. What does the following code do:
def multiply_by_index(numbers):
return [num * i for i, num in
enumerate(numbers)]
a. Multiplies each number by its index
b. Multiplies each index by its corresponding number
c. Multiplies the list by its length
d. Multiplies each number by the sum of all numbers
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,)
74. What will be the output of the following code snippet:
def modify_list(my_list):
my_list.append(4)
my_list.extend([5, 6])
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers)
a. [1, 2, 3, 4, 5, 6] c. [1, 2, 3, 5, 6]
b. [1, 2, 3, 4] d. [1, 2, 3]
75. What is the purpose of the *args parameter in a function
definition?
a. It represents a list of arguments
b. It allows passing a variable number of arguments
c. It is used for keyword arguments
d. It is a required argument for every function
76. What is the correct way to define a function named
calculate_average that takes a list of numbers as an
argument and returns the average?
a. def calculate_average(numbers):
sum = sum(numbers)
return sum / len(numbers)
b. def calculate_average(numbers):
return sum(numbers) /
len(numbers)
c. def calculate_average(numbers):
return sum(numbers) //
len(numbers)
d. def calculate_average(numbers):
avg = sum(numbers) / len(numbers)
return avg
77. What does the following code snippet do:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result)
a. Concatenates the two lists
b. Multiplies each element of the first list by the corresponding
element of the second list
c. Finds the intersection of the two lists
d. Raises a TypeError because lists cannot be added directly
78. Which operator is used to check if a specific element is present in a
list?
a. in c. <>
b. == d. !=
79. What does the * operator do when used with a list?
a. Finds the product of all elements in the list
b. Multiplies the list by a specified number
c. Raises each element of the list to a power
d. Concatenates the list with itself a specified number of times
80. Consider the following code:
numbers = [1, 2, 3]
result = numbers * 2
What is the value of result?
a. [1, 2, 3] c. [1, 2, 3, 1, 2, 3]
b. [2, 4, 6] d. 6
81. What does the following code snippet accomplish:
numbers = [1, 2, 3, 4, 5]
filtered_numbers = [num for num in numbers if
num % 2 == 0]
a. Filters out odd numbers from the list
b. Filters out even numbers from the list
c. Doubles each element of the list
d. Adds 2 to each element of the list
82. What does the following code snippet do:
numbers = [1, 2, 3, 4, 5]
evens = [num for num in numbers if num % 2 ==
0]
a. Doubles each element in the list
b. Filters out even numbers from the list
c. Adds 2 to each element in the list
d. Creates a list of all numbers squared
83. Which conditional statement is used to check if a specific element
is present in a list?
a. if c. elif
b. else d. in
84. Consider the following code:
grades = [85, 92, 78, 95, 88]
result = "Pass" if all(grade >= 70 for grade in
grades) else "Fail"
What is the value of result?
a. “Pass” c. True
b. “Fail” d. False
85. What does the any() function do when used with a conditional
statement in the context of a list?
a. Checks if all elements in the list satisfy the condition
b. Returns True if at least one element satisfies the condition
c. Checks if no elements in the list satisfy the condition
d. Returns True only if all elements are True
86. What does the following code snippet accomplish:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 if num % 2 == 0
else num for num in numbers]
a. Squares all numbers in the list
b. Squares only even numbers in the list
c. Squares odd numbers and doubles even numbers in the list
d. Doubles all numbers in the list
87. What does the following code snippet do:
numbers = [1, 2, 3, 4, 5]
result = [num if num % 2 == 0 else "odd" for
num in numbers]
a. Doubles each element in the list
b. Replaces odd numbers with the string “odd”
c. Checks if all numbers are even
d. Adds 2 to each element in the list
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]
89. Consider the following code:
grades = [85, 92, 78, 95, 88]
result = [grade if grade >= 70 else "Fail" for
grade in grades]
What is the value of result?
a. [85, 92, 78, 95, 88]
b. [“Fail”, 92, “Fail”, 95, 88]
c. [“Pass”, “Pass”, “Fail”, “Pass”, “Pass”]
d. [70, 92, 78, 95, 88]
90. What does the following code snippet accomplish:
numbers = [1, 2, 3, 4, 5]
result = [x * 2 if x % 2 == 0 else x for x in
numbers]
a. Doubles each element in the list
b. Multiplies odd numbers by 2 and leaves even numbers
unchanged
c. Checks if all numbers are even
d. Adds 2 to each element in the list
91. Which of the following is a correct usage of if-else in a list
comprehension to filter elements?
a. [x for x in numbers if x > 0 else 0]
b. [x if x > 0 else 0 for x in numbers]
c. [if x > 0: x else: 0 for x in numbers]
d. [x > 0 for x in numbers]
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()
98. You want to check if a specific item, “Apple,” is present in a list
named groceries. How can you perform this check?
“Apple” in groceries
groceries.check(“Apple”)
groceries.contains(“Apple”)
groceries.has_item(“Apple”)
99. You have a list representing the ages of people. How can you
create a new list containing only the unique ages?
a. ages.unique()
b. set(ages)
c. list(set(ages))
d. ages.remove_duplicates()
100. You have a list named expenses representing monthly expenses.
How can you find the total expenses for the year?
a. total_expenses = sum(expenses) * 12
b. total_expenses = expenses.total()
c. total_expenses = expenses.sum()
d. total_expenses = expenses * 12
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)
102. What does the reduce() function do?
a. Increases the size of a list
b. Combines elements of a list using a specified function
c. Finds the maximum element in a list
d. Filters out elements based on a condition
103. Which function is used to calculate the sum of elements in a list?
a. total()
b. accumulate()
c. sum()
d. reduce()
104. What does the ord() function do?
a. Sorts the elements in a list
b. Converts a character to its Unicode code point
c. Computes the product of elements in a list
d. Checks if all elements in a list are true
105. The cmp() function is used for:
a. Comparing two elements in a list
b. Concatenating two lists
c. Computing the cumulative sum of elements
d. Checking if any element in a list is true
106. What does the max() function return?
a. The maximum element in a list
b. The average of elements in a list
c. The minimum element in a list
d. The sum of elements in a list
107. Which following function is used to find the minimum element in a
list?
a. min()
b. smallest()
c. minimum()
d. get_min()
108. The all() function in is used to:
a. Check if any element in a list is true
b. Check if all elements in a list are true
c. Check if any element in a list is false
d. Check if all elements in a list are false
109. What does the any() function do?
a. Checks if any element in a list is true
b. Checks if all elements in a list are true
c. Checks if any element in a list is false
d. Checks if all elements in a list are false
110. Which function is used to find the length of a list?
a. size()
b. length()
c. count()
d. len()
111. The enumerate() function is used for:
a. Enumerating all elements in a list
b. Generating a list of consecutive integers
c. Creating a dictionary from a list
d. Counting the occurrences of each element in a list
112. What does the accumulate() function do?
a. Calculates the sum of elements in a list
b. Applies a specified function to the cumulative elements of a list
c. Filters out elements based on a condition
d. Sorts the elements in a list
113. The filter() function is used for:
a. Applying a function to each element in a list
b. Removing elements from a list based on a condition
c. Creating a new list with sorted elements
d. Finding the maximum element in a list
114. The map() function is used to:
a. Combine elements of a list using a specified function
b. Apply a function to each element in a list
c. Calculate the product of elements in a list
d. Sort the elements in a list
115. What does the lambda keyword represent?
a. A function definition
b. A reserved word for sorting
c. An anonymous function
d. A keyword for list comprehension
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)
117. The sum() function in can be used with an optional parameter.
What does this parameter represent?
a. Initial value
b. Final value
c. Average value
d. Maximum value
118. What is the purpose of the ord() function when applied to a
character in a list?
a. Finds the position of the character in the list
b. Converts the character to its ASCII value
c. Sorts the list based on the character
d. Checks if the character is present in the list
119. What is the alternative method for comparing two elements in a
list, other than cmp() function?
a. Using the comparison() function
b. Using the compare() function
c. Using the == operator directly
d. Using the cmp_to_key() function
120. Which function is used to find the maximum element in a list of
tuples based on a specific key?
a. max(list, key=lambda x: x[1])
b. maximum(list, key=lambda x: x[1])
c. find_max(list, key=lambda x: x[1])
d. max_element(list, key=lambda x: x[1])
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
122. The all() function returns True if:
a. All elements in the list are True
b. At least one element in the list is True
c. All elements in the list are False
d. At least one element in the list is False
123. What does the any() function return when applied to an empty
list?
a. True
b. False
c. None
d. It raises an error
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
125. The enumerate() function returns a tuple containing:
a. Index and element
b. Element and its ASCII value
c. Index and length of the list
d. Element and its index
126. What is the purpose of the accumulate() function when
applied to a list of numbers?
a. Sorts the numbers in ascending order
b. Computes the cumulative sum of numbers
c. Finds the maximum value in the list
d. Filters out numbers based on a condition
127. The filter() function returns:
a. A new list containing all elements that satisfy a given condition
b. A sorted list based on a specified condition
c. A reversed list based on a given condition
d. A list excluding the first and last elements
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)
129. The lambda function in is also known as:
a. Anonymous function
b. Recursive function
c. Iterative function
d. Named function
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)
131. What is the purpose of the reduce() function in the context of a
list of strings?
a. Combining strings using a specified separator
b. Finding the longest string
c. Sorting the strings alphabetically
d. Reversing the order of strings
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
134. In the enumerate() function, what is the purpose of the second
parameter (start)?
a. It represents the step size for enumerating elements
b. It defines the initial index for enumeration
c. It specifies the ending index for enumeration
d. It indicates the direction of enumeration
135. The accumulate() function can be used with a custom function.
What does this custom function require as parameters?
a. The current element and the next element
b. The current element and the total sum
c. The total sum and the current index
d. The total sum and the next element
136. What is the purpose of the filter() function when applied to a
list of integers?
a. Removes odd numbers from the list
b. Removes even numbers from the list
c. Filters out negative numbers from the list
d. Filters out prime numbers from the list
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
138. How is the lambda function different from a regular function
declaration?
a. Lambda functions cannot take parameters
b. Lambda functions are anonymous and have no name
c. Lambda functions cannot be used with the map() function
d. Lambda functions cannot be used with the filter() function
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])
141. The all() function returns True if:
a. All elements in the list are True
b. At least one element in the list is True
c. All elements in the list are False
d. At least one element in the list is False
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
144. The enumerate() function is often used in conjunction with:
a. The filter() function
b. The map() function
c. List comprehensions
d. The reduce() function
145. What is the output of the accumulate() function when applied
to a list of numbers using the multiply function?
a. The sum of all numbers in the list
b. The product of all numbers in the list
c. The list itself
d. The list sorted in ascending order
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
150. How is the sum() function different from the accumulate()
function?
a. The sum() function computes the cumulative sum, while
accumulate() applies a custom function.
b. The accumulate() function computes the cumulative sum, while
sum() applies a custom function.
c. The sum() function only works with integers, while accumulate()
works with any data type.
d. There is no difference; they are interchangeable.
151. What happens if the enumerate() function is used on a non-
iterable object?
a. It raises an error
b. It returns an empty list
c. It returns None
d. It returns a tuple with index 0 and the non-iterable object
152. The all() function returns True if:
a. All elements in the list are True
b. At least one element in the list is True
c. All elements in the list are False
d. At least one element in the list is False
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
155. The enumerate() function is often used in conjunction with:
a. The filter() function
b. The map() function
c. List comprehensions
d. The reduce() function
156. What is the output of the accumulate() function when applied
to a list of numbers using the multiply function?
a. The sum of all numbers in the list
b. The product of all numbers in the list
c. The list itself
d. The list sorted in ascending order
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
159. 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
160. 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
161. How is the sum() function different from the accumulate()
function?
a. The sum() function computes the cumulative sum, while
accumulate() applies a custom function.
b. The accumulate() function computes the cumulative sum, while
sum() applies a custom function.
c. The sum() function only works with integers, while accumulate()
works with any data type.
d. There is no difference; they are interchangeable.
162. What happens if the enumerate() function is used on a non-
iterable object?
a. It raises an error
b. It returns an empty list
c. It returns None
d. It returns a tuple with index 0 and the non-iterable object
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
164. Which function is used to find the maximum element in a list of
tuples based on a specific key?
a. max(list, key=lambda x: x[1])
b. maximum(list, key=lambda x: x[1])
c. find_max(list, key=lambda x: x[1])
d. max_element(list, key=lambda x: x[1])
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
166. The all() function returns False if:
a. All elements in the list are True
b. At least one element in the list is True
c. All elements in the list are False
d. At least one element in the list is False
167. When using the enumerate() function, what is the purpose of
the start parameter?
a. It defines the initial index for enumeration
b. It specifies the ending index for enumeration
c. It represents the step size for enumerating elements
d. It indicates the direction of enumeration
168. The map() function can be used with multiple iterables. How are
corresponding elements handled?
a. They are combined using the specified function
b. They are ignored, and the function is applied to a single iterable.
c. An error is raised since multiple iterables are not allowed.
d. They are zipped together, and the function is applied to the
resulting tuples.
169. What is the purpose of the accumulate() function when applied
to a list of strings?
a. Combines strings using a specified separator
b. Concatenates strings in the order they appear in the list
c. Computes the cumulative length of strings
d. Sorts the strings alphabetically
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
171. When using the reduce() function with a custom function on a
list of strings, what is the result?
a. A single string concatenating all elements
b. The sum of ASCII values of all characters in the strings
c. An error since the function is not applicable to strings
d. The product of lengths of all strings
172. The lambda function in is restricted to a single line of code:
a. True
b. False
c. It depends on the function complexity
d. Only when used with the map() function
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
174. How is the enumerate() function different from using
range(len(lst)) to iterate over a list?
a. enumerate() returns tuples of index and element, while
range(len(lst)) returns only indices.
b. enumerate() returns only indices, while range(len(lst)) returns
tuples of index and element.
c. There is no difference; they can be used interchangeably.
d. enumerate() is not applicable to lists.
175. The map() function returns:
a. A list of the same size as the original list
b. A list of the doubled size of the original list
c. A single value
d. A tuple containing the mapped values
176. What is the behavior of the filter() function when applied to a
list of integers without a specified function?
a. It includes all positive integers in the filtered list
b. It raises an error since a function is required
c. It filters out all zero values
d. It includes all non-zero integers in the filtered list
177. The reduce() function requires:
a. A binary function (takes two arguments) and an iterable
b. A unary function (takes one argument) and an iterable
c. A ternary function (takes three arguments) and an iterable
d. A function with a variable number of arguments and an iterable
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
181. The all() function returns True if:
a. All elements in the list are True
b. At least one element in the list is True
c. All elements in the list are False
d. At least one element in the list is False
182. How is the accumulate() function different from the
reduce() function?
a. The reduce() function computes the cumulative sum, while
accumulate() applies a custom function.
b. The accumulate() function computes the cumulative sum, while
reduce() applies a custom function.
c. The reduce() function only works with integers, while
accumulate() works with any data type.
d. There is no difference; they are interchangeable.
183. What is the primary purpose of the filter() function when
applied to a list of strings?
a. Filters out strings with numeric characters
b. Filters out empty strings
c. Filters out strings with odd lengths
d. Filters out strings containing vowels
184. The map() function can be used with multiple iterables. How are
corresponding elements handled?
a. They are combined using the specified function
b. They are ignored, and the function is applied to a single iterable
c. An error is raised since multiple iterables are not allowed
d. They are zipped together, and the function is applied to the
resulting tuples
185. How does the reduce() function behave when applied to an
empty list?
a. Raises an error
b. Returns None
c. Returns the identity element (if provided)
d. Returns an empty list
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
187. The lambda function is useful in situations where:
a. A named function is required
b. The function logic is complex and spans multiple lines
c. A short, one-time use function is needed
d. The function needs to be recursive
188. What is the output of the enumerate() function when applied
to an empty list?
a. An empty list
b. None
c. An error
d. A tuple with index 0 and an empty list
189. Which method of list is used to delete element in python?
a. terminate
b. fetch
c. remove
d. delete
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
191. How is the enumerate() function different from using
range(len(lst)) to iterate over a list?
a. enumerate() returns tuples of index and element, while
range(len(lst)) returns only indices.
b. enumerate() returns only indices, while range(len(lst)) returns
tuples of index and element.
c. There is no difference; they can be used interchangeably.
d. enumerate() is not applicable to lists.
192. The map() function returns:
a. A list of the same size as the original list
b. A list of the doubled size of the original list
c. A single value
d. A tuple containing the mapped values
193. What is the behavior of the filter() function when applied to
a list of integers 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
194. When using the reduce() function with a custom function on a
list of strings, what is the result?
a. A single string concatenating all elements
b. The sum of ASCII values of all characters in the strings
c. An error since the function is not applicable to strings
d. The product of lengths of all strings
195. The lambda function is restricted to a single line of code.
a. True
b. False
c. It depends on the function complexity
d. Only when used with the map() function
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
197. How is the enumerate() function different from using
range(len(lst)) to iterate over a list?
a. enumerate() returns tuples of index and element, while
range(len(lst)) returns only indices.
b. enumerate() returns only indices, while range(len(lst)) returns
tuples of index and element.
c. There is no difference; they can be used interchangeably.
d. enumerate() is not applicable to lists.
198. The map() function returns:
a. A list of the same size as the original list
b. A list of the doubled size of the original list
c. A single value
d. A tuple containing the mapped values
199. What is the behavior of the filter() function when applied to
a list of integers 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
200. When using the reduce() function with a custom function on a
list of strings, what is the result?
a. A single string concatenating all elements
b. The sum of ASCII values of all characters in the strings
c. An error since the function is not applicable to strings
d. The product of lengths of all strings
201. The lambda function is restricted to a single line of code.
a. True
b. False
c. It depends on the function complexity
d. Only when used with the map() function
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):
207. You want to count the number of occurrences of a specific word in
a given text stored in a list. What function would you create?
a. def count_word_occurrences(text_list, target_word):
b. def word_frequency(words, search_word):
c. def find_occurrences(word_list, term):
d. def analyze_text_occurrences(text, keyword):
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):
209. In a task management application, you want to mark a task as
completed and remove it from the list of active tasks. What
function signature would you use for this?
a. def complete_task(task_list, task_id):
b. def mark_as_done(tasks, target_task):
c. def remove_completed(task_list, task):
d. def finish_and_remove(task_id, active_tasks):
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):
213. In a classroom application, you need to calculate the average score
of students and identify those who scored above a certain
threshold. What function prototype would you use?
a. def analyze_scores(students_scores, threshold):
b. def student_performance(grades, cutoff):
c. def calculate_average_and_identify(students, limit):
d. def check_above_threshold(scores, threshold):
214. You want to create a function to reverse the order of elements in a
list. What would be the function signature?
a. def reverse_list(lst):
b. def flip_elements(elements):
c. def invert_list_order(data):
d. def backward_sequence(sequence):
215. In a task scheduler application, you need to find the next
upcoming task based on the current date. What function prototype
would you use?
a. def find_upcoming_task(tasks, current_date):
b. def next_task(tasks, today):
c. def get_next_task_based_on_date(task_list, current_date):
d. def identify_upcoming(tasks, date_now):
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):
225. In a grading system, you want to assign letter grades to students
based on their numerical scores. What function prototype would
you use?
a. def assign_letter_grades(scores):
b. def convert_to_letters(grades):
c. def grade_students(numerical_scores):
d. def map_to_letter_grades(grade_list):
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):
228. What would be the function signature to create a function that
counts the occurrences of each unique word in a list of sentences?
a. def count_word_occurrences(sentence_list):
b. def tally_unique_words(sentences):
c. def track_word_frequencies(texts):
d. def analyze_sentence_occurrences(sentence, unique_words):
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):
238. You need to create a function that checks if a given list is a
palindrome; what function prototype would you use?
a. def is_palindrome(input_list):
b. def check_palindromicity(data):
c. def validate_palindrome(input_sequence):
d. def verify_palindrome_sequence(sequence):
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):
242. You need to create a function that calculates the percentage of
students who passed an exam; what function prototype would you
use?
a. def calculate_pass_percentage(exam_results):
b. def analyze_exam_performance(results, passing_threshold):
c. def find_pass_rate(student_scores, passing_score):
d. def determine_percentage_passed(scores_list, passing_score):
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):
244. If you want to create a function that checks if a given list is
monotonic (either entirely non-increasing or non-decreasing),
what function prototype would you use?
a. def is_monotonic(input_list):
b. def check_monotonicity(data):
c. def validate_monotonicity(order_list):
d. def verify_monotonic_sequence(sequence):
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):
248. You want to create a function that checks if a given list is a
geometric progression. What function prototype would you use?
a. def is_geometric_progression(input_list)
b. def check_geometric_progression(data)
c. def validate_geometric_sequence(sequence)
d. def verify_geometricity(elements)
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 d 51 c 101 b 151 a 201 a
2 a 52 b 102 b 152 a 202 a
3 b 53 c 103 c 153 b 203 a
4 a 54 a 104 b 154 c 204 a
5 a 55 d 105 a 155 c 205 a
6 c 56 b 106 a 156 b 206 a
7 b 57 b 107 a 157 a 207 a
8 a 58 c 108 b 158 a 208 a
9 a 59 b 109 a 159 b 209 a
10 a 60 c 110 d 160 b 210 a
11 b 61 a 111 a 161 a 211 a
12 c 62 d 112 b 162 a 212 a
13 c 63 d 113 b 163 c 213 a
14 b 64 d 114 b 164 a 214 a
15 a 65 a 115 c 165 a 215 a
16 c 66 d 116 c 166 d 216 a
17 b 67 c 117 a 167 a 217 a
18 b 68 b 118 b 168 d 218 a
19 b 69 a 119 c 169 b 219 a
20 b 70 c 120 a 170 d 220 a
21 d 71 c 121 a 171 a 221 a
22 b 72 a 122 a 172 a 222 a
23 b 73 a 123 b 173 b 223 a
24 c 74 a 124 a 174 a 224 a
25 b 75 b 125 a 175 a 225 a
26 c 76 b 126 b 176 d 226 a
27 c 77 a 127 a 177 a 227 a
28 c 78 a 128 b 178 a 228 a
29 a 79 b 129 a 179 a 229 a
30 b 80 c 130 a 180 a 230 a
31 a 81 a 131 a 181 a 231 a
32 c 82 b 132 d 182 b 232 a
33 a 83 d 133 a 183 b 233 a
34 c 84 a 134 b 184 d 234 a
35 c 85 b 135 a 185 c 235 a
36 a 86 c 136 c 186 a 236 a
37 b 87 b 137 b 187 c 237 a
38 b 88 a 138 b 188 a 238 a
39 c 89 c 139 b 189 c 239 a
40 c 90 a 140 a 190 b 240 a
41 d 91 b 141 a 191 a 241 a
42 c 92 b 142 b 192 a 242 a
43 b 93 a 143 c 193 d 243 a
44 a 94 a 144 c 194 a 244 a
45 a 95 b 145 b 195 a 245 a
46 b 96 a 146 a 196 b 246 a
47 b 97 b 147 a 197 a 247 a
48 b 98 a 148 b 198 a 248 a
49 a 99 c 149 b 199 d 249 a
50 a 100 a 150 a 200 a 250 a
CHAPTER 8
Tuples
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.
Multiple choice questions
1. What is a tuple in Python?
a. A list of integers
b. An immutable sequence of elements
c. A dictionary
d. A variable
2. How are tuples created in Python?
a. Using square brackets
b. Using parentheses
c. Using curly braces
d. Using angle brackets
3. Can a tuple contain elements of different data types?
a. Yes
b. No
4. How do you access the elements of a tuple?
a. Using square brackets and index
b. Using parentheses and index
c. Using curly braces and index
d. Using angle brackets and index
5. Which of the following is the correct syntax to create an empty
tuple?
a. empty_tuple = ()
b. empty_tuple = []
c. empty_tuple = {}
d. empty_tuple = None
6. Can a tuple be modified after it is created?
a. Yes
b. No
7. What is the result of len(('apple', 'banana',
'cherry'))?
a. 2 c. 4
b. 3 d. 5
8. How do you concatenate two tuples?
a. tuple1 + tuple2
b. tuple1 .concat( tuple2)
c. tuple1 .merge( tuple2)
d. concat(tuple1, tuple2)
9. Which method is used to count the occurrences of a specific
element in a tuple?
a. count() c. index()
b. find() d. search()
10. What is the purpose of the tuple() constructor?
a. To create an empty tuple
b. To convert a list to a tuple
c. To convert a string to a tuple
d. All of the above
11. Which of the following is a valid tuple in Python?
a. (1, 2, 3, 4, 5)
b. 1, 2, 3, 4, 5
c. {1, 2, 3, 4, 5}
d. [1, 2, 3, 4, 5]
12. How do you delete a tuple?
a. del(tuple_name)
b. delete tuple_name
c. remove tuple_name
d. erase tuple_name
13. What is the output of the following code: tuple1 = (1, 2,
3); print(tuple1 * 2)?
a. (1, 2, 3, 1, 2, 3) c. (1, 2, 3, 2, 4, 6)
b. (2, 4, 6) d. 2 4 6
14. Which of the following statements is true about tuple unpacking?
a. It is not possible in Python
b. It allows assigning multiple variables at once
c. It is only used for lists
d. It can only be done using a loop
15. How do you check if an element is present in a tuple?
a. element in tuple
b. tuple.contains(element)
c. tuple.has(element)
d. contains(element, tuple)
16. What is the purpose of using tuples over lists?
a. Tuples have faster access time
b. Tuples are mutable
c. Tuples have a smaller memory footprint
d. Tuples can be sorted
17. What is the result of the expression (1, 2) + (3, 4)?
a. (1, 2, 3, 4) c. (1, 3, 2, 4)
b. (1, 2) + (3, 4) d. Error
18. How do you check if an element is present in a tuple?
a. Using in keyword
b. Using exists keyword
c. Using contains keyword
d. Using is keyword
19. How do you check if an element is present in a tuple?
a. Using in keyword
b. Using exists keyword
c. Using contains keyword
d. Using is keyword
20. What is the purpose of the count method in tuples?
a. To count the number of occurrences of an element
b. To count the total number of elements in the tuple
c. To count the length of the tuple
d. To count the sum of elements in the tuple
21. How do you convert a list to a tuple?
a. tuple(list_variable[])
b. list_variable.to_tuple()
c. list_variable.convert_to_tuple()
d. tuple(list_variable)
22. What happens when you try to modify an element in a tuple?
a. It modifies the element successfully
b. It raises an error since tuples are immutable
c. It deletes the element
d. It appends the element to the end
23. How do you reverse the order of elements in a tuple?
a. reversed(tuple_variable)
b. tuple_variable.reverse()
c. tuple(reversed(tuple_variable))
d. tuple_variable = tuple_variable[::-1]
24. What is the result of the expression len((1, 2, 3))?
a. 3 c. 2
b. 6 d. Error
25. How do you create a tuple with a single element?
a. (1) c. tuple(1)
b. 1, d. (1,)
26. Which method is used to find the index of the first occurrence of
an element in a tuple?
a. find() c. search()
b. index() d. locate()
27. What is the purpose of the sorted function on a tuple?
a. To sort the tuple in descending order
b. To sort the tuple in ascending order
c. To reverse the order of elements in the tuple
d. To shuffle the elements randomly
28. How do you convert a tuple to a list?
a. list(tuple_variable)
b. tuple_variable.to_list()
c. tuple_variable.convert_to_list()
d. list_variable = list(tuple_variable)
29. Which of the following statements is true about tuple unpacking?
a. It cannot be used to assign values to variables
b. It allows assigning multiple variables at once
c. It only works with lists, not tuples
d. It requires the use of curly braces {}
30. What is the output of tuple("Python")?
a. (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
b. ‘Python’
c. (‘Python’,)
d. Error
31. How do you create a shallow copy of a tuple?
a. new_tuple = tuple(old_tuple)
b. new_tuple = old_tuple.copy()
c. new_tuple = copy.copy(old_tuple)
d. All of the above
32. What is the purpose of the any function in relation to tuples?
a. To check if any element in the tuple is true
b. To check if any element in the tuple is false
c. To check if all elements in the tuple are true
d. To check if all elements in the tuple are false
33. How do you convert a tuple to a string?
a. str(tuple_variable)
b. tuple_variable.to_string()
c. tuple_variable.convert_to_string()
d. string(tuple_variable)
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
37. How do you convert a tuple of strings to a single string?
a. ‘ ‘.join(tuple_variable)
b. tuple_variable.join(‘ ‘)
c. join(tuple_variable, ‘ ‘)
d. tuple_variable.concatenate()
38. What is the output of ('apple', 'banana') * 2?
a. (‘apple’, ‘banana’)
b. (‘apple’, ‘banana’, ‘apple’, ‘banana’)
c. (‘appleapple’, ‘bananabanana’)
d. Error
39. How do you convert a tuple to JSON format?
a. json.dumps(tuple_variable)
b. tuple_variable.to_json()
c. tuple_variable.convert_to_json()
d. json.encode(tuple_variable)
40. What is the output of tuple((1, 2, 3))?
a. (1, 2, 3) c. ((1, 2, 3),)
b. 1, 2, 3 d. Error
41. Which method is used to insert an element at a specific index in a
tuple?
a. insert()
b. add()
c. append()
d. None of the above
42. What is the result of the expression (1, 2, 3)[::-1]?
a. (3, 2, 1) c. (1, 3, 2)
b. (1, 2, 3) d. Error
43. What is the purpose of the sum function in relation to tuples?
a. To find the sum of all elements in the tuple
b. To find the average value in the tuple
c. To find the maximum value in the tuple
d. To find the minimum 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)
45. What is the result of the expression (1, 2, 3) * 0?
a. (1, 2, 3) c. Error
b. () d. (0, 0, 0)
46. How do you extract a sublist from a tuple?
a. tuple_variable[start:stop]
b. tuple_variable.extract(start, stop)
c. tuple_variable.sublist(start, stop)
d. tuple_variable[start, stop]
47. What is the result of the expression tuple([1, 2, 3])?
a. (1, 2, 3) c. ((1, 2, 3),)
b. [1, 2, 3] d. Error
48. Which method is used to remove the first occurrence of a specified
element in a tuple?
a. discard() c. remove()
b. delete() d. pop()
49. How do you check if all elements in a tuple are true?
a. all(tuple_variable)
b. tuple_variable.check_all()
c. tuple_variable.are_all_true()
d. all_true(tuple_variable)
50. What is the purpose of the filter function in relation to tuples?
a. To filter out elements based on a condition
b. To filter elements based on their index
c. To filter out all even elements
d. To filter out all odd elements
51. How do you convert a tuple to a dictionary?
a. dictionary(tuple_variable)
b. tuple_variable.to_dict()
c. tuple_variable.convert_to_dict()
d. dict(tuple_variable)
52. Which of the following is a valid way to check if an element is not
present in a tuple?
a. if element not in tuple_variable:
b. if element not tuple_variable:
c. if not element in tuple_variable:
d. if not tuple_variable.contains(element):
53. What is the output of ('a', 'b') < ('c', 'a')?
a. True c. Error
b. False d. (‘c’, ‘a’)
54. What happens when you try to modify an element in a tuple?
a. It is allowed
b. Raises a Type error
c. Automatically creates a new tuple
d. Raises a Value Error
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’)
57. Can a tuple be used as a key in a dictionary?
a. Yes b. No
58. Which built-in function is used to convert an iterable to a tuple?
a. tuple()
b. to_tuple()
c. list()
d. convert_to_tuple()
59. How do you delete the entire tuple named my_tuple?
a. delete my_tuple
b. del my_tuple
c. remove my_tuple
d. my_tuple.delete()
60. What does the count method in tuples return?
a. The total number of elements in the tuple
b. The number of occurrences of a specific element in the tuple
c. The sum of all elements in the tuple
d. The average of all elements in the tuple
61. What is the purpose of the reversed function in the context of
tuples?
a. To reverse the order of elements
b. To remove elements
c. To sort the elements
d. To append elements
62. Which of the following statements is true about tuple unpacking?
a. It is not possible in Python
b. It allows assigning multiple variables at once from a tuple
c. it allows assigning multiple variables at once from a tuple
d. It can only be done with the unpack function
63. What is the output of sum((1, 2, 3, 4))?
a. 10
b. 15
c. (1, 2, 3, 4)
d. 1 + 2 + 3 + 4
64. Which method is used to remove all occurrences of a specific
element from a tuple?
a. remove()
b. delete()
c. clear()
d. filter()
65. What is the output of tuple('hello')[::-1]?
a. (‘o’, ‘l’, ‘l’, ‘e’, ‘h’)
b. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
c. (‘o’, ‘l’, ‘l’, ‘e’, ‘h’, ‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
d. (‘o’, ‘l’, ‘l’, ‘e’, ‘h’, ‘l’, ‘l’, ‘e’, ‘h’, ‘o’)
66. How do you check if an element exists in a tuple?
a. element in my_ tuple
b. my_ tuple .contains(element)
c. my_ tuple. exist(element)
d. has_ element(my _tuple, element)
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
68. What will be the output of tuple(range(5))?
a. (0, 1, 2, 3, 4)
b. [0, 1, 2, 3, 4]
c. (1, 2, 3, 4, 5)
d. [1, 2, 3, 4, 5]
69. What is the output of len(('apple',))?
a. 1
b. 5
c. (‘apple’,)
d. (‘a’, ‘p’, ‘p’, ‘l’, ‘e’)
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]
71. What is the result of tuple('python') == ('p', 'y',
't', 'h', 'o', 'n')?
a. True
b. False
72. What is the output of max(('apple', 'banana',
'orange'))?
a. ‘apple’
b. ‘banana’
c. ‘orange’
d. (‘apple’, ‘banana’, ‘orange’)
73. How do you create a tuple with elements 1 to 5 (inclusive)?
a. tuple(1, 5)
b. tuple(range(1, 5))
c. (1, 2, 3, 4, 5)
d. tuple([1, 2, 3, 4, 5])
74. What is the output of tuple('Hello') + tuple('World')?
a. (‘HelloWorld’)
b. (‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’)
c. (‘Hello’, ‘World’)
d. (‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’)
75. What is the output of tuple('python')[2:5]?
a. (‘t’, ‘h’, ‘o’)
b. (‘t’, ‘h’, ‘o’, ‘n’)
c. (‘t’, ‘o’)
d. (‘t’, ‘h’, ‘o’, ‘n’)
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()
77. What is the output of ('a', 'b', 'c') * 0?
a. ()
b. (‘a’, ‘b’, ‘c’)
c. (‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’)
d. (‘a’, ‘b’, ‘c’, 0)
78. What is the purpose of the any method in tuples?
a. Checks if any element is true
b. Checks if any element is false
c. Checks if any element is zero
d. Checks if any element is non-zero
79. What is the output of tuple('abc') + tuple('123')?
a. (‘abc’, ‘123’)
b. (‘a’, ‘b’, ‘c’, ‘1’, ‘2’, ‘3’)
c. (‘abc123’)
d. (‘a’, ‘b’, ‘c’, 1, 2, 3)
80. What will be the output of tuple('hello') * 2?
a. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
b. (‘hh’, ‘ee’, ‘ll’, ‘ll’, ‘oo’)
c. (‘hello’, ‘hello’)
d. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
81. Which method is used to insert an element at a specific index in a
tuple?
a. insert() c. append()
b. add() d. insert_at()
82. What is the output of tuple(range(1, 10, 2))?
a. (1, 3, 5, 7, 9)
b. (1, 2, 3, 4, 5, 6, 7, 8, 9)
c. (2, 4, 6, 8, 10)
d. (1, 4, 7, 10)
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)
84. What is the output of tuple('abc').count('a')?
a. 0 c. 3
b. 1 d. (‘a’, ‘b’, ‘c’)
85. Which method is used to find the minimum element in a tuple?
a. min() c. find_min()
b. minimum() d. tuple_min()
86. What will be the result of tuple(123)?
a. (‘1’, ‘2’, ‘3’) c. (123)
b. (1, 2, 3) d. (‘123’)
87. What is the output of tuple('hello').index('l')?
a. 2 c. [2, 3]
b. 3 d. (‘l’)
88. How do you convert a tuple to a set?
a. set(my_tuple)
b. my_tuple.to_set()
c. tuple_to_set(my_tuple)
d. set(my_tuple.elements())
89. What is the purpose of the enumerate function in the context of
tuples?
a. To count the occurrences of a specific element
b. To return an iterator of tuples with indices
c. To filter elements based on a condition
d. To create a tuple of enumerations
90. What is the output of the following code?
x = 10
y = 3
print(x % y)
a. 1 c. 3
b. 2 d. 10
91. Which keyword is used to define a function in Python?
a. func c. function
b. define d. def
92. In Python, what does the else clause in a try-except block execute
when an exception is not raised?
a. It executes the code inside the else block
b. It raises a new exception
c. It skips the else block and moves to the finally block
d. It terminates the program
93. What is the purpose of the pass statement in Python?
a. It is used to create a placeholder in code
b. It raises an exception
c. It terminates the program
d. It prints a message
94. Which of the following is not a valid way to comment multiple
lines in Python?
a. Using # at the beginning of each line
b. Using triple double-quotes (“””)
c. Using triple single-quotes (‘’’)
d. Using /* and */
95. What is the output of the following code?
nums = [1, 2, 3, 4]
print(nums[-2])
a. 2 c. 1
b. 3 d. 4
96. What is the purpose of the __str__ method in Python?
a. It converts an object to a string representation
b. It defines the structure of a class
c. It is used for string manipulation
d. It converts a string to an object
97. How can you convert a string to uppercase in Python?
a. str.uppercase() c. str.toUpper()
b. uppercase(str) d. str.upper()
98. Which of the following is the correct way to import a module
named math in Python?
a. import mathModule
b. use math
c. import math
d. math.import
99. What is the purpose of the __init__ method in a Python class?
a. It initializes the class variables
b. It defines the class methods
c. It is used for inheritance
d. It is a reserved keyword
100. How do you check if a key is present in a dictionary in Python?
a. key in dict
b. dict.contains(key)
c. dict.has_key(key)
d. key.exists(dict)
101. What is the result of the expression 2 ** 3 in Python?
a. 6 c. 9
b. 8 d. 5
102. Which of the following statements is used to exit a loop
prematurely in Python?
a. exit c. break
b. terminate d. stop
103. What is the purpose of the with statement in Python?
a. It defines a new class
b. It is used for exception handling
c. It creates a context manager for resource management
d. It is used for string formatting
104. What is the correct way to open a file named “example.txt” in
write mode, creating the file if it does not exist?
a. file = open(“example.txt”, “w”)
b. file = open(“example.txt”, “r”)
c. file = open(“example.txt”, “a”)
d. file = open(“example.txt”, “wb”)
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
106. Which of the following is a correct way to create an empty set in
Python?
a. set.empty()
b. set.create()
c. set()
d. empty_set = {}
107. What is the purpose of the range() function in Python?
a. It generates a sequence of numbers
b. It creates a range object
c. It checks if a number is within a specified range
d. It returns the length of an iterable
108. What is the output of the following code?
x = "Hello"
print(x[1:4])
a. “H” c. “ell”
b. “ell” d. “e”
109. In Python, what is the purpose of the __doc__ attribute?
a. It stores the documentation string of a module, class, or function
b. It is used to access the current date and time
c. It defines the structure of a class
d. It is a reserved keyword
110. What is the result of the expression 5 / 2 in Python 3?
a. 2.5 c. 2.0
b. 2 d. 2.2
111. How do you access the second element of a tuple named
my_tuple?
a. my_tuple[1]
b. my_tuple(2)
c. my_tuple.second
d. my_tuple.index(1)
112. Which method is used to count the occurrences of a specific
element in a tuple?
a. tuple.count(element)
b. tuple.find(element)
c. count(tuple, element)
d. element.count(tuple)
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)
114. Which of the following is a valid way to check if an element is
present in a tuple?
a. element in my_tuple
b. my_tuple.contains(element)
c. my_tuple.has_element(element)
d. element.isIn(my_tuple)
115. What does the tuple() function do in Python?
a. Converts a list to a tuple
b. Creates an empty tuple
c. Converts a string to a tuple
d. All of the above
116. How do you unpack elements from a tuple in a single line?
a. a, b, c = (1, 2, 3)
b. a = (1, 2, 3)
c. a = unpack((1, 2, 3))
d. a, b = (1, 2, 3)
117. Which of the following statements is true about tuples in Python?
a. Tuples are mutable
b. Tuples can have duplicate elements
c. Tuples are enclosed in square brackets [ ]
d. Tuples are ordered and immutable
118. What is the output of the following code:
my_tuple = (10, 20, 30, 40)
print(my_tuple[-2])
a. 30 c. 40
b. 20 d. 10
119. What is the purpose of the len() function when used with a tuple
in Python?
a. It calculates the sum of all elements in the tuple
b. It returns the length of the tuple
c. It finds the maximum value in the tuple
d. It converts the tuple to a list
120. Which of the following is the correct way to create a tuple with
elements 1, 2, and 3?
a. my_tuple = [1, 2, 3]
b. my_tuple = {1, 2, 3}
c. my_tuple = 1, 2, 3
d. my_tuple = tuple(1, 2, 3)
121. What is the result of the expression ('a', 'b') * 3 in
Python?
a. (‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’)
b. (‘a’, ‘b’, 3)
c. [‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’]
d. (‘a’, ‘b’, 9)
122. How do you convert a tuple to a list in Python?
a. list(my_tuple)
b. tuple.toList(my_tuple)
c. my_tuple.convertToList()
d. my_tuple.list()
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)
124. What is the output of the following code:
my_tuple = (1, 2, 3, 4)
print(my_tuple[2:])
a. (1, 2) c. (3, 4)
b. (2, 3, 4) d. (1, 2, 3, 4)
125. Which of the following statements is true about tuple unpacking in
Python?
a. Tuple unpacking can only be done with two variables.
b. Tuple unpacking is not allowed in Python.
c. The number of variables on the left side should match the number
of elements in the tuple.
d. Tuple unpacking can only be done with strings.
126. Which of the following is a correct way to delete a tuple in
Python?
a. del tuple_name
b. tuple_name.remove()
c. tuple_name.delete()
d. tuple_name.clear()
127. How do you concatenate two tuples in Python?
a. tuple1 + tuple2
b. concat(tuple1, tuple2)
c. combine(tuple1, tuple2)
d. tuple1.concatenate(tuple2)
128. Which of the following statements is true about tuples in Python?
a. Tuples can be modified after creation.
b. Tuples can have elements of different data types.
c. Tuples are unordered collections of elements.
d. Tuples are always enclosed in square brackets [ ].
129. In Python, what is the purpose of the tuple() function?
a. It converts a list to a tuple.
b. It creates an empty tuple.
c. It converts a string to a tuple.
d. All of the above
130. What is the output of the following code:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result)
a. (1, 2, 3, 4, 5, 6)
b. [(1, 2, 3), (4, 5, 6)]
c. (5, 7, 9)
d. [(1, 2, 3, 4, 5, 6)]
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
132. Which of the following is the correct way to check if a tuple is
empty in Python?
a. if tuple:
b. if len(tuple) == 0:
c. if tuple.empty():
d. if not tuple:
133. How do you convert a tuple to a string in Python?
a. str(tuple)
b. tuple.toString()
c. convertToString(tuple)
d. string(tuple)
134. What is the output of the following code:
tuple1 = (10, 20, 30)
tuple2 = tuple1
tuple2 += (40,)
print(tuple1)
a. (10, 20, 30)
b. (10, 20, 30, 40)
c. (10, 20, 30, [40])
d. (40, 30, 20, 10)
135. Which of the following statements is true about indexing in tuples?
a. Tuples in Python cannot be indexed
b. Indexing in tuples starts from 1
c. Negative indexing is not allowed in tuples
d. Elements in a tuple are accessed using square brackets and an
index
136. How do you check if a specific element is not present in a tuple in
Python?
a. if element not in my_tuple:
b. if not my_tuple.contains(element):
c. if my_tuple.isNotIn(element):
d. if my_tuple.not_in(element):
137. Which of the following is a correct way to create a tuple with
repeated elements?
a. repeated_tuple = (1, 1, 1, 1)
b. repeated_tuple = tuple(1, 1, 1, 1)
c. repeated_tuple = (1 * 4)
d. repeated_tuple = tuple(4 * 1)
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
139. What is the output of the following code:
tuple1 = (1, 2, 3, 4, 5)
tuple2 = tuple1[1:4]
print(tuple2)
a. (2, 3, 4)
b. (1, 2, 3)
c. (2, 3, 4, 5)
d. (3, 4, 5)
140. How do you reverse the order of elements in a tuple in Python?
a. reversed_tuple = tuple.reverse(my_tuple)
b. reversed_tuple = my_tuple[::-1]
c. reversed_tuple = reverseTuple(my_tuple)
d. reversed_tuple = my_tuple.reverse()
141. In Python, what is the purpose of the enumerate() function
when used with a tuple?
a. It counts the occurrences of a specific element in the tuple.
b. It returns an enumerated object containing tuples with index and
element pairs.
c. It sorts the elements in the tuple.
d. It converts the tuple to a list.
142. Which of the following is a correct way to create a tuple with
elements 1, 2, and 3?
a. my_tuple = (1, 2, 3)
b. my_tuple = [1, 2, 3]
c. my_tuple = {1, 2, 3}
d. my_tuple = 1, 2, 3
143. How do you convert a tuple to a dictionary in Python?
a. tuple.to_dict()
b. dict(tuple)
c. tuple.as_dict()
d. convert_to_dict(tuple)
144. How can you check if a tuple is immutable in Python?
a. if tuple.is_immutable():
b. if not tuple.mutable():
c. if not isinstance(tuple, MutableSequence):
d. if isinstance(tuple, ImmutableSequence):
145. Which of the following statements is true about slicing in tuples?
a. Tuples support only forward slicing
b. Tuples support both forward and backward slicing
c. Tuples do not support slicing
d. Slicing in tuples always starts from 1
146. What is the result of the expression tuple("python")[-1]?
a. ‘p’ c. ‘o’
b. ‘n’ d. ‘y’
147. What is the purpose of the min() function when applied to a tuple
in Python?
a. It finds the smallest element in the tuple.
b. It returns the sum of all elements in the tuple.
c. It finds the length of the longest element in the tuple.
d. It checks if the tuple is empty.
148. What is the output of the following code?
my_tuple = (10, 20, 30)
result = my_tuple * 0
print(result)
a. () c. None
b. (0, 0, 0) d. (10, 20, 30)
149. How do you check if a tuple is a subset of another tuple in Python?
a. tuple1.is_subset(tuple2)
b. set(tuple1).issubset(set(tuple2))
c. subset(tuple1, tuple2)
d. tuple1.issubset(tuple2)
150. Which method is used to insert an element at a specific position in
a tuple in Python?
a. tuple.insert(index, element)
b. tuple.add(index, element)
c. insert_element(tuple, index, element)
d. element.insert(tuple, index)
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)\
152. What is the purpose of the tuple() constructor in Python?
a. It creates an empty tuple
b. It converts a list to a tuple
c. It converts a string to a tuple
d. All of the above
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()
154. What is the purpose of the tuple.count() method in Python?
a. It counts the occurrences of a specific element in the tuple
b. It returns the total number of elements in the tuple
c. It checks if the tuple is empty
d. It calculates the sum of all elements in the tuple
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)
156. What is the result of the expression tuple("abc") * 3 in
Python?
a. (‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’)
b. ((‘a’, ‘b’, ‘c’), (‘a’, ‘b’, ‘c’), (‘a’, ‘b’, ‘c’))
c. [‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’]
d. TypeError: can’t multiply sequence by non-int of type ‘tuple’
157. Which method is used to convert a tuple to lowercase in Python?
a. tuple.lower()
b. lower(tuple)
c. tuple.convert_to_lowercase()
d. tuple_lower(tuple)
158. How can you check if a tuple is a superset of another tuple in
Python?
a. if tuple1.is_superset(tuple2):
b. if set(tuple1).issuperset(set(tuple2)):
c. superset(tuple1, tuple2)
d. if tuple1.superset(tuple2)
159. How do you check if a tuple is disjoint from another tuple in
Python?
a. if tuple1.disjoint(tuple2):
b. if set(tuple1).isdisjoint(set(tuple2)):
c. disjoint(tuple1, tuple2)
d. if tuple1.is_disjoint(tuple2)
160. What is the purpose of the tuple.extend() method in
Python?
a. It adds elements to the end of the tuple
b. It concatenates two tuples
c. It extends the length of the tuple
d. There is no extend() method for tuples
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)
162. What is the output of the following code:
tuple1 = ('a', 'b', 'c')
tuple2 = ('x', 'y', 'z')
result = tuple1 + tuple2
print(result[-1])
a. ‘c’ c. ‘x’
b. ‘z’ d. ‘a’
163. What is the primary difference between a tuple and a list in
Python?
a. Tuples are mutable, lists are immutable.
b. Tuples are ordered, lists are unordered.
c. Tuples can have duplicate elements, lists cannot.
d. Tuples can contain elements of different data types, lists cannot.
164. Which method is used to convert a list into a tuple?
a. tuple() c. to_tuple()
b. convert_tuple() d. list_to_tuple()
165. What is the output of the following code:
tuple1 = (1, 2, 3, 4, 5)
del tuple1
print(tuple1)
a. (1, 2, 3, 4, 5)
b. Error: tuple1 is not defined
c. ()
d. None
166. In Python, which operator is used for concatenating two tuples?
a. & c. *
b. + d. //
167. How can you unpack elements from a tuple into separate
variables?
a. a, b = unpack(tuple)
b. a, b = tuple.unpack()
c. a, b = *tuple
d. a, b = tuple
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.
169. Which method is used to clear all elements from a tuple?
a. tuple.clear()
b. tuple.empty()
c. tuple.remove_all()
d. del tuple[:]
170. What will be the result of the expression (1, 2, 3) < (1, 2,
4)?
a. True
b. False
c. Error
d. None
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
173. What does the tuple() constructor do when applied to a list?
a. Converts the list into a string.
b. Converts the list into a set.
c. Converts the list into a tuple.
d. Converts the list into a dictionary.
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()
176. What is the purpose of the tuple() constructor without any
arguments?
a. Creates an empty tuple.
b. Converts a list into a tuple.
c. Returns a tuple containing integers from 0 to n-1.
d. Constructs a tuple with a single element.
177. If tuple1 = (1, 2, 3) and tuple2 = (4, 5), what is
the result of the expression tuple1 += tuple2?
a. (1, 2, 3, 4, 5)
b. (1, 2, 3) + (4, 5)
c. ((1, 2, 3), (4, 5))
d. Error
178. How do you create a shallow copy of a tuple?
a. Using the copy() method.
b. new_tuple = tuple(original_tuple)
c. new_tuple = original_tuple.copy()
d. Shallow copy is not possible for tuples.
179. What is the output of the code snippet tuple('hello')?
a. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
b. (‘hello’)
c. (‘h’, ‘e’, ‘l’, ‘l’, ‘l’, ‘o’)
d. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘o’)
180. How can you convert a tuple into a string in Python?
a. str(tuple)
b. tuple.str()
c. “”.join(tuple)
d. tuple.join(“”)
181. What will be the output of the code
print(tuple(range(5)))?
a. (0, 1, 2, 3, 4)
b. (1, 2, 3, 4, 5)
c. (0, 1, 2, 3, 4, 5)
d. Error
182. What will be the result of the expression ('a', 'b') ==
('a', 'b', 'c')?
a. True c. Error
b. False d. None
183. In Python, how can you check if a tuple is empty?
a. if tuple:
b. if not tuple:
c. if tuple is empty:
d. if tuple.empty():
184. What method is used to find the smallest element in a tuple?
a. min()
b. smallest()
c. minimum()
d. find_min()
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(‘,’)
186. Which method is used to get the hash value of a tuple?
a. hash() c. hash(tuple)
b. tuple.hash() d. get_hash()
187. How can you delete a specific element from a tuple?
a. Tuples are immutable; elements cannot be deleted.
b. tuple.remove(element)
c. del tuple[element]
d. tuple.delete(element)
188. What is the purpose of the tuple() constructor when applied to
a dictionary?
a. Converts the dictionary into a tuple of keys.
b. Converts the dictionary into a tuple of values.
c. Converts the dictionary into a tuple of key-value pairs.
d. Raises an error; cannot convert a dictionary to a tuple.
189. What will be the result of the code sorted(('cat', 'dog',
'elephant'))?
a. [‘cat’, ‘dog’, ‘elephant’]
b. (‘cat’, ‘dog’, ‘elephant’)
c. [‘cat’, ‘dog’, ‘elephant’]
d. (‘cat’, ‘dog’, ‘elephant’)
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()
191. What is the output of the code tuple(range(2, 11, 2))?
a. (2, 4, 6, 8, 10) c. (2, 6, 10)
b. (2, 4, 8, 10) d. (2, 4, 6, 8)
192. If tuple1 = ('apple', 'banana', 'cherry'), what will
be the result of tuple1[1:]?
a. (‘banana’, ‘cherry’)
b. (‘banana’)
c. (‘apple’, ‘banana’)
d. (‘banana’, ‘cherry’, ‘apple’)
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
195. What is the purpose of the tuple.__contains__() method?
a. Checks if the tuple is empty.
b. Checks if a specific element is present in the tuple.
c. Returns the number of occurrences of a specified element.
d. Checks if all elements in the tuple are of the same data type.
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))
197. If tuple1 = (1, 2, 3) and tuple2 = (4, 5), what is the
result of the expression tuple1[1:] + tuple2[::-1]?
a. (2, 3, 5, 4)
b. (2, 3, 4, 5)
c. (2, 3, 5, 4, 3, 2, 1)
d. (2, 3, 4)
198. How can you create a tuple with elements from two existing tuples,
without modifying the original tuples?
a. tuple1.extend(tuple2)
b. tuple1.append(tuple2)
c. tuple1 + tuple2
d. tuple1.join(tuple2)
199. What will be the result of the code tuple('hello
world'.split())?
a. (‘hello’, ‘world’)
b. (‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’)
c. (‘hello world’)
d. (‘hello’, ‘world’)
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()
202. What is the purpose of the tuple.__iter__() method?
a. Checks if the tuple is iterable.
b. Returns an iterator for the tuple.
c. Iterates through the tuple elements.
d. Creates a new iterator for the tuple.
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.
204. What will be the result of the code tuple(tuple('abcd'))?
a. (‘a’, ‘b’, ‘c’, ‘d’)
b. (‘abcd’)
c. (‘a’, ‘b’, ‘c’, ‘c’)
d. (‘abcd’,)
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()
206. How can you check if a tuple is a subset of another tuple?
a. tuple1.is_subset(tuple2)
b. set(tuple1).issubset(tuple2)
c. tuple1.subset(tuple2)
d. tuple1 <= tuple2
207. What is the result of the expression tuple('abc') +
tuple('def')?
a. (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’)
b. (‘abcdef’)
c. (‘abc’, ‘def’)
d. (‘a’, ‘b’, ‘c’, ‘def’)
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)
209. What is the purpose of the tuple.__str__() method?
a. Converts the tuple into a string representation.
b. Returns the length of the tuple.
c. Checks if the tuple is empty.
d. Creates a string from the elements of the tuple.
210. If tuple1 = (1, 2, 3) and tuple2 = (4, 5, 6), what is
the result of tuple1 * 2 * 3 + tuple2?
a. (1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 6)
b. (1, 2, 3, 2, 4, 6)
c. (1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5)
d. Error
211. What is the output of the following code?
my_tuple = (1, 2, 3)
print(my_tuple * 2)
a. (1, 2, 3, 1, 2, 3)
b. [1, 2, 3, 1, 2, 3]
c. (2, 4, 6)
d. [2, 4, 6]
212. How do you access the elements of a tuple?
a. Using square brackets []
b. Using curly braces {}
c. Using angle brackets <>
213. Can a tuple have elements of different data types?
a. Yes b. No
214. What is the primary advantage of using tuples over lists in
Python?
a. Tuples have a higher performance.
b. Tuples use less memory.
c. Tuples are more versatile.
d. Tuples can be modified more easily.
215. Which of the following methods is used to remove the last element
from a tuple?
a. remove()
b. pop()
c. delete()
d. discard()
216. What is the output of the following code:
my_tuple = (1, 2, 3, 4, 5)
reversed_tuple = my_tuple[::-1]
print(reversed_tuple)
a. (1, 2, 3, 4, 5)
b. (5, 4, 3, 2, 1)
c. (5, 4, 3, 2)
d. (5, 4, 3)
217. Which of the following methods is used to insert an element at a
specific index in a tuple?
a. insert()
b. add()
c. append()
d. attach()
218. What will be the output of the following code:
my_tuple = ('apple', 'orange', 'banana')
index = my_tuple.index('orange')
print(index)
a. 0
b. 1
c. 2
d. Error
219. Which of the following is the correct way to create a shallow copy
of a tuple?
a. copied_tuple = copy(my_tuple)
b. copied_tuple = my_tuple.copy()
c. copied_tuple = my_tuple.clone()
d. copied_tuple = deepcopy(my_tuple)
220. What will be the result of the following code:
tuple_a = (1, 2, 3, 4, 5)
del tuple_a
print(tuple_a)
a. (1, 2, 3, 4, 5)
b. Error
c. None
d. The code will run without an issue
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)
222. What is the output of the following code:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[10:])
a. Error c. (1, 2, 3, 4, 5)
b. () d. (5,)
223. What will be the result of the following code:
tuple_a = (1, 2, 3)
tuple_b = tuple_a
tuple_b += (4, 5)
print(tuple_a)
a. (1, 2, 3) c. (4, 5)
b. (1, 2, 3, 4, 5) d. Error
224. What is the output of the following code:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[-3:])
a. (3, 4, 5) c. (2, 3, 4, 5)
b. (1, 2, 3) d. (4, 5)
225. What is the output of the following code:
tuple_a = (1, 2, 3)
tuple_b = tuple_a
tuple_b = tuple_b + (4, 5)
a. (1, 2, 3) c. (4, 5)
b. (1, 2, 3, 4, 5) d. Error
226. Which of the following is the correct syntax to create an empty
tuple?
a. empty_tuple = {}
b. empty_tuple = []
c. empty_tuple = ()
d. empty_tuple = None
227. Which method is used to extend a tuple with elements from
another iterable?
a. add() c. append()
b. extend() d. attach()
228. What is the purpose of the tuple() function when applied to a
set?
a. To create a set from a tuple.
b. To convert a set to a tuple.
c. To merge a set and a tuple.
d. To find the intersection of a set and a tuple
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)
230. What is the output of the following code:
tuple_a = (1, 2, 3, 4, 5)
print(tuple_a[1:5:2])
a. (2, 4) c. (2, 4, 5)
b. (2, 3) d. (1, 3, 5)
231. What will be the result of the following code:
tuple_a = (1, 2, 3)
tuple_b = (4, 5, 6)
result = tuple_a * 2 + tuple_b
print(result.count(2))
a. 2 c. 0
b. 3 d. 1
232. What is the purpose of the join() method when applied to a
tuple?
a. To concatenate tuples.
b. To join two tuples into one.
c. There is no join() method for tuples.
d. To convert the tuple elements to a string.
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)
236. How do you check if a tuple is immutable?
a. tuple.is_mutable()
b. type(tuple) == ‘immutable’
c. isinstance(tuple, tuple)
d. is_immutable(tuple)
237. What is the purpose of the index() method when applied to a
tuple?
a. To find the index of the first occurrence of a specific element.
b. To get the index of the last occurrence of a specific element.
c. To set the index of a particular element.
d. To check if an element exists at a specific index.
238. How do you check if a tuple is iterable?
a. if tuple.is_iterable():
b. if isinstance(tuple, Iterable):
c. if tuple.has_iterator():
d. if tuple.iterator() is not None:
239. What is the purpose of the tuple() constructor function when
applied to a range object?
a. To create a range from a tuple.
b. To convert a range to a tuple.
c. To merge a range and a tuple.
d. To find the intersection of a range and a tuple.
240. How do you check if a specific element is present at least once in a
tuple?
a. if element is tuple:
b. if tuple.contains(element):
c. if element in tuple:
d. if tuple.has_element(element):
241. How do you check if all elements in a tuple are integers?
a. if all(isinstance(element, int) for element in tuple):
b. if tuple.isintegers():
c. if tuple.all(int):
d. if elements_are_integers(tuple):
242. What is the purpose of the += operator when applied to tuples in
Python?
a. To add two tuples element-wise.
b. To concatenate two tuples.
c. To subtract one tuple from another.
d. Tuples do not support the += operator.
243. How do you find the average of elements in a tuple named
numbers?
a. average = sum(numbers) / len(numbers)
b. average = numbers.avg()
c. average = average(numbers)
d. average = mean(numbers)
244. What is the purpose of the tuple() constructor function when
applied to a list of numbers?
a. To create a list of numbers.
b. To convert a list of numbers to a single tuple.
c. To merge all numbers into a tuple.
d. To find the average of the numbers in the list.
245. How do you find the sum of all elements in a tuple named values?
a. sum(values) c. total(values)
b. values.sum() d. add(values)
246. How do you find the last index of a specific element in a tuple?
a. tuple.last_index(element)
b. tuple.index(element, -1)
c. last(tuple, element)
d. tuple[-1].index(element)
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)
248. How do you check if a tuple is sorted in ascending order?
a. if tuple.is_sorted():
b. if sorted(tuple) == tuple:
c. if tuple.sort() == tuple:
d. if ascending(tuple):
249. What is the purpose of the tuple() constructor function when
applied to a dictionary of key-value pairs?
a. To create a dictionary from a tuple.
b. To convert a dictionary to a tuple.
c. To merge a dictionary and a tuple.
d. To find the intersection of a dictionary and a tuple.
250. What is the output of the following code:
tuple_a = (3, 1, 4, 1, 5, 9)
sorted_tuple = sorted(tuple_a)
print(sorted_tuple)
a. (3, 1, 4, 1, 5, 9) c. (1, 1, 3, 4, 5, 9)
b. (9, 5, 4, 3, 1, 1) d. (1, 1, 3, 4, 5, 9, 4)
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
1 b 51 d 101 b 151 b 201 b
2 b 52 a 102 c 152 d 202 b
3 a 53 c 103 c 153 c 203 d
4 a 54 b 104 a 154 a 204 a
5 a 55 b 105 c 155 c 205 b
6 b 56 a 106 c 156 a 206 b
7 b 57 a 107 a 157 a 207 a
8 a 58 a 108 b 158 b 208 a
9 a 59 b 109 a 159 b 209 a
10 d 60 a 110 a 160 d 210 a
11 a 61 c 111 a 161 b 211 a
12 a 62 b 112 a 162 b 212 a
13 a 63 a 113 c 163 b 213 a
14 b 64 a 114 a 164 a 214 b
15 b 65 a 115 d 165 b 215 b
16 c 66 a 116 a 166 b 216 b
17 a 67 a 117 d 167 d 217 a
18 a 68 a 118 b 168 d 218 b
19 a 69 a 119 b 169 d 219 b
20 a 70 d 120 c 170 a 220 b
21 d 71 a 121 a 171 b 221 a
22 b 72 c 122 a 172 a 222 b
23 c 73 b 123 a 173 c 223 a
24 a 74 b 124 c 174 b 224 a
25 d 75 a 125 c 175 a 225 b
26 b 76 a 126 a 176 a 226 c
27 b 77 a 127 a 177 a 227 b
28 a 78 a 128 b 178 b 228 b
29 b 79 b 129 d 179 a 229 a
30 a 80 a 130 a 180 c 230 a
31 d 81 a 131 a 181 a 231 a
32 a 82 a 132 a 182 b 232 c
33 a 83 a 133 a 183 b 233 d
34 c 84 b 134 a 184 a 234 d
35 a 85 a 135 d 185 a 235 b
36 a 86 b 136 a 186 c 236 c
37 b 87 a 137 a 187 a 237 a
38 b 88 a 138 b 188 c 238 b
39 a 89 b 139 a 189 a 239 b
40 a 90 a 140 b 190 b 240 c
41 d 91 d 141 b 191 a 241 a
42 a 92 a 142 a 192 a 242 b
43 a 93 a 143 a 193 c 243 a
44 b 94 d 144 b 194 a 244 b
45 b 95 c 145 c 195 b 245 a
46 a 96 a 146 b 196 b 246 b
47 a 97 d 147 a 197 a 247 d
48 c 98 c 148 a 198 c 248 b
49 a 99 a 149 b 199 a 249 b
50 a 100 a 150 a 200 b 250 c
CHAPTER 9
Dictionaries
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.
Multiple choice questions
1. What is a Python dictionary?
a. A data structure that stores elements in a linear order.
b. A data structure that stores elements in a random order.
c. A data structure that stores key-value pairs.
d. A data structure that stores elements in a sorted order.
2. How do you create an empty dictionary in Python?
a. my_dict = {}
b. my dict = dict()
c. my_dict = dict([])
d. my dict = []
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
4. How can you verify the existence of a key in a dictionary without
triggering an error if it is not present?
a. Use a for loop
b. Use a try and except block
c. Use the in keyword
d. Use the contain method
5. What method is used to remove a key-value pair from a
dictionary?
a. remove()
b. pop()
c. delete()
d. discard()
6. Which of the following methods is used to retrieve all the keys
from a dictionary?
a. keys()
b. get_keys()
c. all_keys()
d. retrieve_keys()
7. What happens when you try to add a new key-value pair to a
dictionary with an existing key?
a. It overwrites the existing value.
b. It appends the new value to the existing value.
c. It raises a ValueError exception.
d. It raises a KeyError exception.
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
10. Which of the following is true about dictionary keys in Python?
a. Dictionary keys must be integers.
b. Dictionary keys must be unique.
c. Dictionary keys can only be strings.
d. Dictionary keys are automatically sorted.
11. Which method can be used to add a key-value pair to a dictionary
if the key does not exist, and set a default value if it does?
a. add()
b. insert()
c. setdefault()
d. append()
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.
13. What does the update() method do for dictionaries in Python?
a. It merges two dictionaries into one.
b. It updates the value of a specific key.
c. It removes a key-value pair from the dictionary.
d. It sorts the dictionary in ascending order.
14. What will the popitem() method do in a dictionary?
a. Remove the last item from the dictionary.
b. Remove the first item from the dictionary.
c. Remove a specific item based on the key provided.
d. It has unpredictable behavior; it may remove any item.
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.
16. Which of the following is a valid way to create a copy of a
dictionary?
a. new_dict = dict(old_dict)
b. new_dict = old_dict.copy()
c. new_dict = old_dict.clone()
d. new_dict = old_dict
17. How do you check the number of key-value pairs in a dictionary?
a. len(my_dict)
b. count(my_dict)
c. size(my_dict)
d. length(my_dict)
18. Which of the following statements is true about dictionary values
in Python?
a. Dictionary values must be integers.
b. Dictionary values must be unique.
c. Dictionary values can be of any data type, including duplicates.
d. Dictionary values can only be strings.
19. How can you check if a specific value exists in a dictionary?
a. Use the contains() method.
b. Use a loop to iterate through the values.
c. Use the in keyword.
d. Use the value() method.
20. What is the purpose of the clear() method in Python
dictionaries?
a. It sorts the dictionary in ascending order.
b. It removes all items from the dictionary.
c. It returns a new dictionary containing the same items.
d. It creates a shallow copy of the dictionary.
21. Given a dictionary my_dict, what method would you use to
retrieve a list of all key-value pairs in the dictionary?
a. get_items()
b. values()
c. items()
d. key_value_pairs()
22. Which method can be used to retrieve a list of all keys in a
dictionary?
a. get_keys()
b. keys()
c. all_keys()
d. list_keys()
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.
27. What is the purpose of the values() method in Python
dictionaries?
a. It returns a list of all values in the dictionary.
b. It returns a list of all keys in the dictionary.
c. It returns the number of key-value pairs in the dictionary.
d. It sorts the dictionary in ascending order by values.
28. How can you check if a dictionary is empty?
a. Use the empty() method.
b. Use the is_empty() method.
c. Use the len() function and check if it equals 0.
d. Use the has_items() method.
29. What will the copy() method do for a dictionary?
a. It creates a deep copy of the dictionary.
b. It creates a shallow copy of the dictionary.
c. It creates a reversed copy of the dictionary.
d. It creates a sorted copy of the dictionary.
30. Which of the following methods can be used to remove a specific
item from a dictionary?
a. remove() c. discard()
b. delete() d. pop()
31. What is the time complexity for looking up a key in a dictionary
using the in keyword?
a. O(1)
b. O(n)
c. O(log n)
d. O(n^2)
32. What is the purpose of the items() method in Python
dictionaries?
a. It returns a list of all items in the dictionary.
b. It returns a list of all keys in the dictionary.
c. It returns a list of all values in the dictionary.
d. It sorts the dictionary in ascending order by keys.
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.
36. What is the purpose of the popitem() method in Python
dictionaries?
a. It removes a specific key-value pair from the dictionary.
b. It removes the first key-value pair from the dictionary.
c. It removes the last key-value pair from the dictionary.
d. It removes all key-value pairs from the dictionary.
37. How do you check if a specific key exists in a dictionary?
a. Use the has_key() method.
b. Use the exists() method.
c. Use the in keyword.
d. Use the find_key() method.
38. What is the purpose of the defaultdict class from the
collections module?
a. It allows you to create dictionaries with default values for all
keys.
b. It allows you to create dictionaries with default values for
specific keys.
c. It allows you to create dictionaries with keys that cannot be
modified.
d. It allows you to create dictionaries with sorted keys.
39. What is the time complexity for adding an item to a dictionary
using the my_dict[key] = value syntax?
a. O(1) c. O(log n)
b. O(n) d. O(n^2)
40. 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)
41. What is the purpose of the copy.deepcopy() function from the
copy module?
a. It creates a shallow copy of a dictionary.
b. It creates a deep copy of a dictionary, including nested
dictionaries.
c. It sorts the keys of a dictionary in ascending order.
d. It returns the list of keys in a dictionary.
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.
46. How can you check if a specific value exists in a dictionary’s
values?
a. Use the contains() method.
b. Use a loop to iterate through the values.
c. Use the in keyword.
d. Use the value_exists() method.
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.
51. How do you remove a specific key-value pair from a dictionary
using the pop() method?
a. By specifying the value to be removed.
b. By specifying the key to be removed.
c. By specifying both the key and value to be removed.
d. By removing the last key-value pair in the dictionary.
52. What is the purpose of the copy() method in Python
dictionaries?
a. It creates a deep copy of the dictionary.
b. It creates a shallow copy of the dictionary.
c. It creates a reversed copy of the dictionary.
d. It creates a sorted 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”]
63. Can you make an empty dictionary in Python?
a. YES b. NO
64. Which of the following will create an empty dictionary?
a. DICT() c. DICT=()
b. DICT{} d. DICT={}
65. Can you create a dictionary using the dict() function?
a. YES b. No
66. Which of the following is the correct syntax to make a dictionary
using the dict () inbuilt function?
a. Dict = dict{1: ‘hello’, 2: ‘everyone’}
b. Dict = dict(1: ‘hello’, 2: ‘everyone’)
c. Dict = dict({1: ‘hello’, 2: ‘everyone’})
67. Is it always important to write pairs in inverted commas?
a. Yes b. No
68. Can you include lists and tuples as pairs in the dictionary?
a. Yes b. No
69. What will be the output of the following code:
D={1:7,2:"everyone"}
print(D[2])
a. 7 c. 2
b. 1 d. Everyone
70. Apart from indexing which alternative function is used to access
the pair value?
a. pair() c. get()
b. key() d. None
71. How do you use the get() function to access the pair values?
a. D={1:7,2:”everyone”}
print(D.get(2))
b. D={1:7,2:”everyone”}
print(D=get(2))
c. D={1:7,2:”everyone”}
print(get(2))
72. Can you add items to the existing dictionary?
a. Yes b. No
73. Suppose we want to have the following output:
{0: 'welcome', 2: 'to', 3: 'include help'}
How will you add these items to the already created empty dictionary?
a. Dict[0]=’welcome’
Dict[2] = ‘to’
b. Dict[3]=’includehelp’
[0]=’welcome’
[2]=’to’
[3] = ‘include help’
c. Dict[0]=[0:’welcome’]
Dict[1]
d. =[2:’to’]
Dict[2] =[3: ‘include help’]
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)
77. Which method is used to remove the entire dictionary?
a. pop() c. delete_all()
b. delete() d. clear()
78. Which method is an alternative method to remove the particular
item from Python?
a. pop() c. delete_all()
b. delete() d. clear()
79. Can you make a list as a key in the dictionary?
a. Yes b. No
80. Which function gives the total number of elements in the list?
a. total() c. len()
b. sum() d. keys()
81. What does the dict.items() method do?
a. It returns all the keys of the dictionary as a tuple
b. It returns all the keys and pairs of the dictionary as a tuple
c. It returns all the pairs of the dictionary as a tuple
82. What does the dict.values() method do?
a. It returns all the keys of the dictionary as a tuple
b. It returns all the keys and pairs of the dictionary as a tuple
c. It returns all the pairs of the dictionary as a tuple
83. Suppose you want to modify a particular key or value which of the
following function you will use?
a. modify() c. change()
b. update() d. new()
84. What does the dict.keys() method do?
a. It returns all the keys of the dictionary as a tuple
b. It returns all the keys and pairs of the dictionary as a tuple
c. It returns all the pairs of the dictionary as a tuple
85. Which keyword is used to check the particular key in the
dictionary?
a. is c. check if
b. in d. None
86. What will be the output of the following code?
d = {'x': 1, 'y': 2, 'z': 3}
a = d.pop('y')
print(a, d)
a. 2 {‘x’: 1, ‘z’: 3}
b. 0 {‘x’: 1, ‘z’: 3}
c. 2 {‘x’: 1, ‘y’ : 2, ‘z’: 3}
d. None
87. How do you check if a key exists in a dictionary?
a. Using the in keyword (Correct Answer)
b. Using the exists() method
c. Using the has_key() method
d. Using the check_key() method
88. In Python, dictionaries are immutable.
a. False b. True
89. Items are accessed by their position in a dictionary and All the
keys in a dictionary must be of the same type.
a. True b. False
90. Dictionary keys must be immutable.
a. True b. False
91. __________________provides meta data about data elements.
a. Data dictionary
b. Data flow diagram
c. Decision tree
d. Decision flow
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
95. Which of the following is used to delete an element from
dictionary?
a. pop()
b. delete
c. remove
d. None of the above
96. We can repeat values of keys in dictionary.
a. True b. False
97. clear() method is used to delete the dictionary.
a. True b. False
98. Which statement is used to create an empty dictionary?
a. d1 ={} c. d1=dict{}
b. d1=() d. d1=[]
99. Dictionary is a _________data type.
a. Sequence
b. Mapping
c. Ordered
d. None of the above
100. Dictionaries are flexible in nature, means elements can be added
or removed from it.
a. True b. False
101. Choose the output of the following:
d1={"a":50," b":50}
d1={"a":500," b":50}
print(d1>d2)
a. True
b. False
c. Error
d. None of the above
102. Only values (without keys) can be printed in dictionary?
a. True b. False
103. Which datatype is based on keys and values concept in Python?
a. Tuple c. Dictionary
b. List d. String
104. In dictionary keys and values are separated by _______
a. Semicolon (;) c. Comma (,)
b. Dot (.) d. Colon (:)
105. All elements in a dictionary are separated by __________
a. Semicolon (;) c. Comma (,)
b. Dot (.) d. Colon (:)
106. Both keys and values are unique in dictionaries.
a. True b. False
107. Which of the following is an example of a dictionary in Python?
a. L= []
b. C= ()
c. D= {}
d. None of the above
108. 1,2,3 are ________ in the following dictionary:
D= { 1:" one", 2:" two", 3:" three"}
a. Keys
b. Items
c. None of above
109. Keys in dictionary are _______.
a. Mutable c. Antique
b. Immutable d. Integers
110. What type of error is returned by the following code:
A= {'a': 'apple', 'b': 'banana', 'c': "cat"}
Print(a[1])
a. Key Error
b. Syntax error
c. Key not found error
d. Not found error
111. Write the output of the following:
a= {'a': 'apple', 'b': 'banana', 'c': "cat"}
a['a'] = 'Anar'
print(a)
a. Error
b. {‘a’: ’apple’, ‘a’: ‘Anar’, ‘b’: ‘banana’ ,’c’ : ’cat’}
c. {‘a’: ’apple’, ‘b’: ‘banana’, ‘c’: “cat”}
d. None of the above
112. Traversing a dictionary can be done using __________.
a. If statement
b. Loop
c. Jump statement
d. None of the above
113. Which of the following data type falls under mapping?
a. List c. String
b. Tuple d. dictionary
114. Which of the following is NOT true about dictionary?
a. Items stored in dictionary are unordered.
b. Duplicate keys are allowed in dictionary.
c. Keys of dictionary are immutable and values are mutable.
d. Keys of dictionary can be string, integer or combination of both.
115. Select the correct statement:
i. A dictionary can have duplicates values for different keys.
ii. The values of dictionary can be accessed using indexes.
a. i True, ii false
b. i false, ii true
c. both true
d. both false
116. Which of the following is the correct syntax for defining a
dictionary?
a. D={[‘a’,10],[‘b’,20]}
b. D={(‘a’,10),(‘b’,20)}
c. D={‘a’,10:‘b’,20}
d. D={‘a’:10,‘b’:20}
117. The length of dictionary is equal to:
a. Length of values of dictionaries
b. Length of keys of dictionaries
c. Length of keys:value pairs of the dictionary
d. Length of index of dictionary
118. Method used to return all keys of dictionary is:
a. Key() c. Value()
b. Keys() d. Values()
119. Method which returns all the items (key:value) of dictionary as
tuple is
a. dict() c. get()
b. items() d. keys()
120. When we add a new key:value pair to dictionary, it increases the
size of dictionary beyond its original size, and hence an error
occurs.
a. True b. False
121. We cannot use list as key for a dictionary because:
i. Lists are mutable and keys are immutable.
ii. Lists are collection of items and keys are
represented with single item.
a. Both true c. i true, ii false
b. Both false d. i false, ii true
122. Slicing cannot be applied on dictionaries are
a. Dictionary stores items as keys:value pair
b. Dictionary is not sequence, items stored in it are unordered
c. Dictionary keys are immutable
d. Dictionary keys cannot taken as list
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)
126. Predict the output of given code:
d1={'a':10,'b':20}
d2={'c':30,'d':40}
d1.update(d2)
print(d1)
a. ={‘a’:10,’b’:20,{‘c’:30,’d’:40}}
b. ={{‘a’:10,’b’:20},{‘c’:30,’d’:40}}
c. ={‘a’:10,’b’:20,‘c’:30,’d’:40}
d. ={‘a’:10,’b’:20,[‘c’:30,’d’:40]}
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
129. What will be the output of following code:
d = {'c':30,'d':40}
print(d.items())
a. dict_items[(‘c’,30),(‘d’,40)]
b. dict_items{(‘c’,30),(‘d’,40)}
c. dict_items[[‘c’,30),(‘d’,40]]
d. dict_items[‘c’->30),(‘d’->40]
130. Look at the given Dictionary:
d1 = {'a':10,'b':20,'c':30,'d':40}
Which of the following code will delete value corresponding to key
‘c’?
a. d1.pop(‘c’)
b. del(d1[‘c’])
c. d1.remove(‘c’)
d. a and b
e. all a, b and c
131. Find the output of given code:
S={'jan':23,'feb':21,'mar':30,'apr':52}
print('mar' in s)
a. true c. 0
b. false d. {}
132. Find the output of given code:
S={'san':40,'man':78,'dan':72,'wan':65}
print(s['pan'])
a. Name error c. Key error
b. Value error d. Index error
133. Find the output of given code:
S={'san':40,'man':78,'dan':72,'wan':65}
s.clear()
print(s)
a. Name c. {}
b. error d. dict_item()
134. Find the output of given code:
S={'san':40,'man':78,'dan':72,'wan':65}
for a in s:
print(a,end=" ")
a. 40 78 72 65
b. San mam dan wan
c. Error
d. No output
135. For given dictionary d with items {1:30,2:60,3:90}, what will
happen if following code will be executed: del d?
a. delete all the items from d
b. delete entire d
c. generate error
d. delete first item from d
136. What will be the output of following code:
d = {'c':30,'d':40}
print(d.values())
a. dict_values[(30,40)}
b. dict_values((30,,40))
c. dict_values(30,40)
d. dict_values[30,40]
137. What is the primary purpose of a dictionary in Python?
a. Storing data in a sorted manner
b. Storing data in key-value pairs
c. Storing data in a stack
d. Storing data in a sorted manner
138. How are dictionary elements enclosed in Python?
a. Parentheses ()
b. Square brackets []
c. Curly braces {}
d. Angle brackets <>
139. Which of the following is not a valid dictionary key in Python?
a. Integer c. String
b. Float d. List
140. How can you access the value associated with a specific key in a
dictionary?
a. Using the index
b. Using a for loop
c. Using the key inside square brackets []
d. Using the value() method
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
142. How do you add a new key-value pair to an existing dictionary in
Python?
a. Using the append() method
b. Using the add() method
c. Using the insert() method
d. By assigning a value to a new key
143. Which method is used to remove a key-value pair from a
dictionary in Python?
a. Using the append() method
b. Using the add() method
c. Using the insert() method
d. By assigning a value to a new key
144. What happens when you use the pop() method on a dictionary
with a non-existent key?
a. It returns None
b. It raises a KeyError
c. It removes the last item in the dictionary
d. It returns False
145. Which method is used to get a list of all keys in a dictionary?
a. keys() c. all_keys()
b. get_keys() d. dict_keys()
146. What does the values() method return in a dictionary?
a. A list of all values
b. A list of all keys
c. A list of key-value pairs
d. A list-like object containing all values
147. Which method is used to get a list of all key-value pairs in a
dictionary?
a. items() c. get_items()
b. key_value_pairs() d. pairs()
148. How do you create a shallow copy of a dictionary?
a. Using the clone() method
b. Using the copy() method
c. Using the deepcopy() method
d. Using the duplicate() method
149. Which method is used to clear all key-value pairs from a
dictionary?
a. clear() c. delete_all()
b. remove_all() d. erase()
150. What does the len() function return when applied to a
dictionary?
a. The number of key-value pairs in the dictionary
b. The sum of all values in the dictionary
c. The number of keys in the dictionary
d. The number of values in the dictionary
151. How do you merge two dictionaries into one in Python?
a. Using the merge() method
b. Using the extend() method
c. Using the combine() method
d. Using the update() method
152. Which of the following statements create a dictionary?
a. D = {}
b. D = {“john”:40, “peter”:45}
c. D = {40:”john”, 45:”peter”}
d. All of the mentioned
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
155. Which of these about a dictionary is false?
a. The values of a dictionary can be accessed using keys
b. The keys of a dictionary can be accessed using values
c. Dictionaries aren’t ordered
d. Dictionaries are mutable
156. Which of the following is not a declaration of the dictionary?
a. {1: ‘A’, 2: ‘B’}
b. Dict([[1,”A”],[2,”B”]])
c. {1,”A”,2”B”}
d. { }
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
160. Which of the statements about dictionary values is false?
a. More than one key can have the same value
b. The values of the dictionary can be accessed as dict[key]
c. Values of a dictionary must be unique
d. Values of a dictionary can be a mixture of letters and numbers
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.
162. If a is a dictionary with some key-value pairs, what does
a.popitem() do?
a. Removes an arbitrary element
b. Removes all the key-value pairs
c. Removes the key-value pair for the key given as an argument
d. Invalid method for 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
166. Running the code sorted(my_dictionary, reverse =
True) on a dictionary named my_dictionary will return
results sorted in what order ?
a. Ascending order (A-Z), by key
b. Ascending order (A-Z), by value
c. Descending order (Z-A), by key
d. Descending order (Z-A), by value
167. Guess output of the below Python code:
a = {(1,2):1,(2,3):2}
print(a[1,2])
a. Key Error
b. 1
c. {(2,3):2}
d. {(1,2):1}
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)
169. The code below has a Python function writing to a dictionary.
What will it print in the end?
fruit = {}
def addone(index):
if index in fruit:
fruit[index] += 1
else:
fruit[index] = 1
addone('Apple')
addone('Banana')
addone('apple')
print (len(fruit))
a. 1 c. 3
b. 2 d. 4
170. What will be the output of the following Python coding snippet:
arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print (sum)
a. 1 c. 3
b. 2 d. 4
171. How will the Python dictionary in the below code behave?
my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4
sum = 0
for k in my_dict:
sum += my_dict[k]
print (sum)
Choose the right answer:
a. 7 c. 3
b. syntax error d. 6
172. Which of the following is not a method of the dictionary object in
Python?
a. get() c. values()
b. keys() d. popitem()
173. What will the following Python dictionary code print in its result?
box = {}
jars = {}
crates = {}
box['biscuit'] = 1
box['cake'] = 3
jars['jam'] = 4
crates['box'] = box
crates['jars'] = jars
print (len(crates[box]))
a. 1 c. 4
b. 3 d. Type Error
174. What will be the output of the Python code given below:
dict = {'c': 97, 'a': 96, 'b': 98}
for _ in sorted(dict):
print (dict[_])
a. 96 98 97 c. 98 97 96
b. 96 97 98 d. NameError
175. Will the ID of a copied Python dictionary object change:
rec = {"Name" : "Python", "Age":"20"}
r = rec.copy()
print(id(r) == id(rec))
Choose the correct answer:
a. True c. 0
b. False d. 1
176. What will be the result of the below Python code:
rec = {"Name" : "Python Programmer",
"Age":"20", "Addr" : "NJ", "Country" : "USA"}
id1 = id(rec)
del rec
rec = {"Name" : "Python Programmer",
"Age":"20", "Addr" : "NJ", "Country" : "USA"}
id2 = id(rec)
print(id1 == id2)
a. True c. 1
b. False d. Exception
177. What will be the output of the following code?
d= {'c':30,'d':40}
print(d.keys())
a. dict_keys([‘c’,’d’])
b. dict_keys((‘c’,’d’))
c. dict_keys[‘c’,’d’]
d. dict_keys([‘c’,’d’)
178. Sumit created a dictionary d with items {1:10,2:30,3:40,4:40,5:10}.
Now he wants to find the total of all values of dictionary items.
Help him select appropriate code to do so:
a. d.sum(d.values())
b. d.sum(d.items())
c. sum(d.values())
d. sum(d.items())
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
186. What is the difference between the keys() and values()
methods in Python dictionaries?
a. The keys() method returns a list of all the keys in the dictionary,
while the values() method returns a list of all the values in the
dictionary.
b. The keys() method returns a set of all the keys in the dictionary,
while the values() method returns a set of all the values in the
dictionary.
c. The keys() method returns a tuple of all the keys in the
dictionary, while the values() method returns a tuple of all the
values in the dictionary.
d. None of the above
187. What is the difference between the items() and popitem()
methods in Python dictionaries?
a. The items() method returns a list of all the key-value pairs in the
dictionary, while the popitem() method removes and returns a
random key-value pair from the dictionary.
b. The items() method returns a set of all the key-value pairs in the
dictionary, while the popitem() method removes and returns a
random key-value pair from the dictionary.
c. The items() method returns a tuple of all the key-value pairs in
the dictionary, while the popitem() method removes and returns a
random key-value pair from the dictionary.
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
192. Which of the following is the correct way to copy a Python
dictionary?
a. d1 = d2
b. d1 = d2.copy()
c. d1 = dict(d2)
d. All of the mentioned
193. Which of the following is the correct way to clear a Python
dictionary?
a. d.clear()
b. d = {}
c. del d
d. All of the mentioned
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
197. Which of the following is the correct way to check if a dictionary is
empty?
a. if d:
b. if len(d) == 0:
c. if d == {}:
d. All of the mentioned
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
199. Which of the following is a valid dictionary comprehension in
Python?
a. {key: value for key, value in d.items()}
b. {key: value for key in d.keys()}
c. {key: value for value in d.values()}
d. All of the mentioned
200. Which of the following is a valid way to iterate over a Python
dictionary?
a. for key, value in d.items():
b. for key in d.keys():
c. for value in d.values():
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()
203. Which of the following is the correct way to check if a dictionary is
equal to another dictionary?
a. d1 == d2
b. d1 is d2
c. d1.keys() == d2.keys() and d1.values() == d2.values()
d. All of the mentioned
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
205. Which of the following is the correct way to update a dictionary
with a new key-value pair 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
206. Which of the following is the correct way to update a dictionary
with a new value for an existing key?
a. d[key] = new_value
b. d.update({key: new_value})
c. Both (a) and (b)
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
215. Which of the following is the correct way to sort a Python
dictionary by its values?
a. d = sorted(d.items(), key=lambda x: x[1])
b. d = sorted(d.keys(), key=lambda x: d[x])
c. d = sorted(d.values(), key=lambda x: x)
d. All of the mentioned
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
220. Which of the following is the correct way to update a Python
dictionary with the values of another dictionary, but only if the
keys do not exist in the original dictionary?
a. d1.update(d2, ignore_existing=True)
b. d1.update(d2, overwrite=False)
c. d1.setdefault(d2)
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
223. Which of the following is the correct way to serialize a Python
dictionary to a JSON string?
a. import json
b. json.dumps(d)
c. Both (a) and (b)
d. None of the above
224. Which of the following is the correct way to deserialize a JSON
string to a Python dictionary?
a. import json
b. json.loads(json_string)
c. Both (a) and (b)
d. None of the above
225. Which of the following is the correct way to use a Python
dictionary as a default value for an argument?
a. def func(arg=d):
b. def func(arg: d):
c. def func(arg=dict(d)):
d. All of the mentioned
226. Which of the following is the correct way to use a Python
dictionary as a counter?
a. d = {}
b. for key in keys:
c. d[key] += 1
d. All of the mentioned
227. Which of the following about dictionary is false?
a. The values of dictionary can be accessed using keys
b. The keys of a dictionary can be accessed using values
c. Dictionary is mutable
d. None of above
228. Which of the following is not a valid key in a Python dictionary?
a. None
b. True
c. False
d. All of the mentioned are valid keys in a Python dictionary
229. Which of the following is the correct way to iterate over a
dictionary in reverse order?
a. for key in reversed(d.keys()):
b. for key in d.keys()[::-1]:
c. Both (a) and (b)
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
231. Which of the following is the correct way to check if a dictionary is
empty?
a. not d
b. d == {}
c. d.isEmpty()
d. All of the above
232. Which of the following is the correct way to clear a dictionary?
a. d.clear()
b. del d
c. d = {}
d. All of the mentioned
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
237. Which of the following is the correct way to update a dictionary
with the values of another dictionary, overwriting any existing
keys?
a. d1.update(d2)
b. d1.update(d2, overwrite=True)
c. d1.setdefault(d2, overwrite=True)
d. None of the above
238. In Python, dictionary are immutable.
a. True b. False
239. Which of the following methods can be used to iterate over the
keys in a Python dictionary?
a. for key in dict:
b. for key in dict.keys():
c. for key, value in dict.items():
d. All 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
244. Which of the following is the best way to reverse a Python
dictionary?
a. Using the reverse() method
b. Using the reversed() function
c. Using the items() method
d. None of the above
245. What is the output of following Python Program:
D = {1 : 1, 2 : '2', '1' : 1, '2' : 3}
D['1'] = 2
print(D [D [D [str (D[1])] ] ] )
a. 2 c. ‘2’
b. 3 d. keyError
246. Consider below dictionary:
D = {'foo':100, 'bar':200, 'baz':300}
What is the result of this statement:
D{'bar': 'baz'}
a. It raises an exception
b. [200, 300]
c. 200 300
d. (200, 300)
247. What is the output of following Python Programs?
D={1: [1,2,3], 2: (4,6,8)}
D[1].append(4)
print (D[1], end == " ")
L= [D[2]]
L.append(10)
D[2] = tuple[L]
print (D[2])
a. [1, 2, 3, 4] [4, 6 ,8 ,10]
b. [1, 2, 3, 4] ( (4, 6 ,8 ,10)
c. [1, 2, 3, 4] (4, 6 ,8 ,10)
d. [1, 2, 3, 4] TypeError: tuples are immutable
248. What is the output of the following Python Program:
dictionary1 = { 'Articleworld':1,
'Facebook':2, 'Microsoft':3}
dictionary2 = { 'Atic':1, 'Google':2,
'Youtube':3}
dictionary1.update(dictionary2);
for key, values in dictionary1. items():
print(key, values, end = " ")
a. Microsoft 3 Atic 1 Articleworld1 Google 2
b. Microsoft 3 Atic 1 Articleworld1 Google 2 Youtube 3 Facebook
2
c. Articleworld1 Google 2 Youtube 3 Facebook 2
d. None of these
249. Select the correct way to print Emma’s age:
Student = { 1: {'name': 'Emma', 'age': '27' ,
'sex': 'Female'},
2: {'name': 'Mike', 'age':
'22' , 'sex': 'Male'}}
a. Student[0][1]
b. Student[0][“age”]
c. Student[1][“age]
d. None of these
250. What is the output of the following python program?
Dict={}
print(all(dict))
a. An exception is thrown
b. False
c. True
d. {}
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 c 51 b 101 c 151 d 201 a
2 a 52 b 102 a 152 d 202 b
3 a 53 a 103 c 153 b 203 c
4 c 54 c 104 d 154 a 204 b
5 b 55 a 105 c 155 b 205 b
6 a 56 c 106 b 156 c 206 c
7 a 57 c 107 c 157 a 207 c
8 b 58 a 108 a 158 b 208 a
9 b 59 b 109 b 159 d 209 a
10 b 60 c 110 a 160 c 210 a
11 c 61 a 111 d 161 c 211 a
12 a 62 c 112 b 162 a 212 a
13 a 63 a 113 d 163 c 213 a
14 a 64 d 114 b 164 b 214 c
15 c 65 a 115 a 165 c 215 d
16 b 66 c 116 d 166 c 216 a
17 a 67 a 117 c 167 b 217 c
18 c 68 a 118 b 168 a 218 c
19 c 69 d 119 b 169 c 219 c
20 b 70 c 120 b 170 d 220 a
21 c 71 a 121 c 171 d 221 d
22 b 72 a 122 b 172 d 222 b
23 b 73 a 123 d 173 d 223 c
24 b 74 c 124 a 174 a 224 c
25 b 75 a 125 c 175 b 225 d
26 c 76 a 126 c 176 a 226 d
27 a 77 d 127 b 177 a 227 b
28 c 78 a 128 d 178 c 228 a
29 b 79 b 129 a 179 a 229 c
30 d 80 c 130 d 180 d 230 a
31 a 81 b 131 a 181 a 231 d
32 a 82 c 132 c 182 a 232 d
33 b 83 b 133 c 183 b 233 c
34 b 84 a 134 b 184 a 234 c
35 a 85 b 135 b 185 b 235 a
36 c 86 a 136 a 186 a 236 a
37 c 87 a 137 b 187 a 237 a
38 a 88 b 138 c 188 a 238 b
39 a 89 b 139 c 189 a 239 d
40 a 90 a 140 c 190 d 240 a
41 b 91 a 141 c 191 b 241 b
42 b 92 a 142 d 192 d 242 c
43 d 93 b 143 d 193 d 243 d
44 b 94 d 144 b 194 a 244 d
45 c 95 a 145 d 195 b 245 b
46 c 96 a 146 d 196 c 246 a
47 d 97 b 147 a 197 d 247 b
48 b 98 a 148 b 198 a 248 d
49 a 99 b 149 a 199 d 249 c
50 a 100 a 150 a 200 d 250 a
CHAPTER 10
File Handling
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.
Multiple choice questions
1. What is the primary purpose of file handling in Python?
a. To create new files
b. To manipulate data within files
c. To print data to the console
d. To perform mathematical operations
2. A text file stores information in __________ characters.
a. ASCII c. Both (a) and (b)
b. Unicode d. None of the above
3. In text files, each line of text is terminated with a special character
known as ___________.
a. EOL c. EEF
b. EOF d. All of the above
4. What function is used to open a file in Python for reading?
a. open(“file.txt”, “w”)
b. open(“file.txt”, “r”)
c. open(“file.txt”, “a”)
d. open(“file.txt”, “x”)
5. How do you close a file in Python after you have finished reading
or writing?
a. close(file) c. fclose(file)
b. file.close() d. file.close_file()
6. Which mode should be used when opening a file for reading and
writing in Python?
a. “r+” c. “a+”
b. “w+” d. “x+”
7. A _________ file is just a file that contains information in the same
format in which the information is held in its memory.
a. Text file
b. Binary file
c. Word file
d. None of the above
8. Which function is used to write data onto a file?
a. write()
b. writelines()
c. Both (a) and (b)
d. None of the above
9. Which function is used to write data to a file in Python?
a. read() c. write()
b. append() d. save()
10. Which method is commonly used to read a line from a text file in
Python?
a. readline() c. readlines()
b. read() d. readall()
11. What is the purpose of the with statement when working with files
in Python?
a. It is used for creating a new file.
b. It is used for writing to a file.
c. It ensures that the file is properly closed after its suite finishes
executing.
d. It is used for reading a file line by line.
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.
20. Which of the following is not a valid file mode in Python?
a. “x” c. “rw”
b. “a+” d. “rb”
21. When opening a binary file, what mode should you use in Python?
a. “r” c. “rb”
b. “w” d. “wb”
22. What does the readlines() method do in Python file handling?
a. Reads a single line from the file.
b. Reads the entire file as a string.
c. Reads all lines of the file into a list.
d. Reads the first n lines of the 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.
24. Which method is used to write a sequence of strings to a text file in
Python?
a. write() c. writeall()
b. writelines() d. writestring()
25. What function is used to create a new directory in Python?
a. make_dir()
b. create_directory()
c. mkdir()
d. newdir()
26. What does the flush() method do in Python file handling?
a. Closes the file.
b. Writes the file contents to disk.
c. Clears the file content.
d. Reads the file content.
27. Which of the following is the correct way to open a file in binary
write mode and ensure it is created if it does not exist?
a. file = open(“file.bin”, “w”)
b. file = open(“file.bin”, “wb”)
c. file = open(“file.bin”, “a”)
d. file = open(“file.bin”, “r”)
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.
32. Which method is used to rename a file in Python?
a. rename_file()
b. move_file()
c. os.rename()
d. change_file_name()
33. When using the with statement to open a file, is it necessary to
explicitly close it?
a. Yes, it is necessary.
b. No, the file is automatically closed when the block exits.
c. It depends on the Python version.
d. Only if an exception is raised.
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.
35. What function is used to determine the size of a file in bytes in
Python?
a. file_size() c. os.size()
b. get_size() d. os.path.getsize()
36. In Python, what does the truncate() method do?
a. Closes the file.
b. Resizes the file to the specified size.
c. Deletes the file from the file system.
d. Reads the entire file.
37. How do you create a new directory and all its parent directories in
Python?
a. Use the mkdir() function with the parents=True argument.
b. Use the create_directory() method with the recursive=True
argument.
c. Use the makedirs() function with the exist_ok=True argument.
d. Use the os.mkdir() function with the make_parents=True
argument.
38. Which method checks whether a file is a directory or a regular file
in Python?
a. is_dir() c. is_directory()
b. is_file() d. is_regular_file()
39. What does the os.path.abspath() function do in Python?
a. Returns the absolute path of the current working directory.
b. Returns the absolute path of a specified file.
c. Checks if a file is absolute or relative.
d. Converts a relative path to an absolute path.
40. How do you remove a directory and its contents in Python?
a. Use the rmdir() function.
b. Use the remove_directory() function.
c. Use the os.remove() function.
d. Use the shutil.rmtree() function.
41. What does the os.path.basename() function return in
Python?
a. The directory part of a file path.
b. The filename without the directory part.
c. The file extension.
d. The root directory.
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.
44. What is the purpose of the os.path.isdir() function in
Python?
a. It checks if a file is readable.
b. It checks if a file is executable.
c. It checks if a path is a directory.
d. It checks if a file is empty.
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.
46. What does the os.remove() function do in Python?
a. Creates a new file.
b. Moves a file from one directory to another.
c. Removes (deletes) a file from the file system.
d. Renames a file.
47. What is the purpose of the os.path.getatime() function in
Python?
a. Returns the size of a file in bytes.
b. Returns the access time of a file in seconds since the epoch.
c. Checks if a path is a directory.
d. Returns the modification time of a file.
48. Which function is used to check if a path exists in Python and is a
directory?
a. os.path.is_directory()
b. os.path.exists()
c. os.path.isfile()
d. os.path.isdir()
49. What is the purpose of the os.path.getmtime() function in
Python?
a. Returns the creation time of a file.
b. Returns the modification time of a file.
c. Checks if a path is absolute or relative.
d. Returns the size of a file in bytes.
50. How can you create a new directory in Python and its parent
directories if they do not exist?
a. Use the os.mkdir() function.
b. Use the os.makedirs() function with the exist_ok=True argument.
c. Use the create_directory() method.
d. Use the newdir() function.
51. What is the purpose of the os.path.getctime() function in
Python?
a. Returns the size of a file in bytes.
b. Returns the modification time of a file.
c. Returns the creation time of a file in seconds since the epoch.
d. Checks if a path is a directory.
52. Which function is used to rename a directory in Python?
a. rename_directory()
b. move_directory()
c. os.rename()
d. change_directory_name()
53. How do you check if a path is a symbolic link in Python?
a. Use the os.path.issymlink() function.
b. Use the os.path.islink() function.
c. Use the is_symbolic_link() method.
d. Use the file.is_symlink() method.
54. What is the purpose of the os.path.getsize() function in
Python?
a. Returns the size of a file in bytes.
b. Returns the absolute path of a file.
c. Returns the modification time of a file.
d. Checks if a path is a directory.
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.
58. How do you check if a file is empty in Python?
a. Use the file.is_empty() method.
b. Use the os.is_empty() function.
c. Use the os.path.getsize() function and compare to 0.
d. Use the file.size() method.
59. What does the os.path.isabs() function return if the given
path is absolute?
a. True c. None
b. False a. An error message
60. How can you check if a directory is empty in Python?
a. Use the is_empty_directory() function.
b. Use the os.is_empty_dir() function.
c. Use the os.listdir() function and check the length of the list.
d. Use the directory.is_empty() method.
61. What function is used to get the current working directory in
Python?
a. current_directory()
b. os.get_cwd()
c. os.getcwd()
d. get_current_directory()
62. How do you create a hard link to a file in Python?
a. Use the hardlink() function from the os module.
b. Use the create_hard_link() method.
c. Use the os.link() function.
d. Use the file.create_hardlink() method.
63. What is the purpose of the os.path.normpath() function in
Python?
a. Converts a relative path to an absolute path.
b. Returns the absolute path of a specified file.
c. Normalizes a path, removing redundant separators and references
to the current directory.
d. Checks if a path is a directory.
64. How can you check if a file or directory is hidden in Python?
a. Use the file.is_hidden() method.
b. Use the os.path.is_hidden() function.
c. Use the os.access() function with a special flag for hidden files.
d. Use the file.isHidden() method.
65. What does the os.path.split() function do in Python?
a. Returns the file extension of a path.
b. Splits a path into its directory and file components.
c. Returns the size of a file in bytes.
d. Check if a path is a directory.
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
68. In Python, what is the purpose of the write() method when
opening a file in write mode?
a. It appends data to the file.
b. It reads data from the file.
c. It overwrites the file with new data.
d. It checks if the file exists.
69. What is the purpose of the writelines() method in Python file
handling?
a. It reads a list of lines from a file.
b. It writes a list of lines to a file.
c. It reads the entire file as a string.
d. It creates a list of lines from a file.
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.
72. What is the purpose of Python’s read() method when reading a
file?
a. It reads a single line from the file.
b. It reads the entire file as a string.
c. It reads the first n characters from the file.
d. It reads the entire file as a list of lines.
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
74. When using the with statement to open a file, is it necessary to
explicitly close it?
a. Yes, it is required
b. No, the file is automatically closed when the block exits
c. It depends on the Python version
d. Only if an exception is raised
75. What is the purpose of the readline() method in Python file
handling?
a. It reads the entire file
b. It reads the first line of the file
c. It reads a specific line from the file
d. It reads the last line of the file
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.
81. What is the purpose of the os.path.getsize() function in
Python?
a. Returns the size of a file in bytes
b. Returns the access time of a file in seconds since the epoch
c. Checks if a path is a directory
d. Returns the file extension of a path
82. How do you create a backup copy of a file in Python without
overwriting the original file?
a. Use the backupfile() function
b. Use the copyfile() function from the shutil module
c. Use the file.copy() method
d. Use the file.backup() method
83. What function is used to change the permissions of a file in
Python?
a. change_permissions()
b. set_permissions()
c. os.chmod()
d. file.set_permissions()
84. How do you write a tab character to a file in Python?
a. Using the tab() function
b. Using the \t escape sequence
c. Using the \\t escape sequence
d. Using the t character
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
90. What does the writelines() method do in Python when used
with a list of lines?
a. Writes a single string with all lines concatenated
b. Writes each line as a separate file
c. Writes the list as a single line in the file
d. Writes each line from the list to the file
91. How do you write a newline character to a file in Python?
a. Using the newline() function
b. Using the n character
c. Using the \\n escape sequence
d. Using the nline method
92. What is the purpose of the os.path.normcase() function in
Python?
a. Returns the size of a file in bytes
b. Converts a relative path to an absolute path
c. Normalizes the case of a path to lowercase
d. Checks if a path is a directory
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
122. Which method is used to read a file line by line?
a. read(1) c. readline()
b. readlines(1) d. line()
123. When you open a file in append 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. Random position
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
136. Which of the following is true about the shutil.rmtree
function in Python?
a. It deletes individual files.
b. It deletes only empty directories.
c. It recursively deletes directories and their contents.
d. It renames directories.
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”)
138. What is the purpose of the os.remove function in Python?
a. To rename a file.
b. To copy a file.
c. To delete a file.
d. To create a new file.
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”)
140. What is the purpose of the shutil.rmtree function in
Python?
a. To copy a directory.
b. To rename a directory.
c. To delete a directory and its contents.
d. To move a 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”)
143. What is the purpose of the os.rmdir function in Python?
a. To copy a directory
b. To rename a directory
c. To delete an empty directory
d. To move a directory
144. How can you check if a directory exists before deleting it in Python
using the os module?
a. os.isdir(“directory”)
b. os.directory_exists(“directory”)
c. os.path.exists(“directory”)
d. os.exists_directory(“directory”)
145. What is the purpose of the os.path.exists function in
Python?
a. To check if a file or directory exists.
b. To create a new file.
c. To rename a file or directory.
d. To copy a file or 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”)
147. What is the purpose of the shutil.copy function in Python?
a. To move a file.
b. To create a new file.
c. To copy a file.
d. To delete a file.
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”)
149. What is the purpose of the shutil.copytree function in
Python?
a. To rename a directory.
b. To copy a directory and its contents.
c. To delete a directory.
d. To move a 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”)
153. What is the purpose of the os.path.isdir function in Python?
a. To check if a file or directory exists
b. To create a new file
c. To rename a file or directory
d. To check if a path is a directory
154. What is the purpose of Python’s seek() function when used
with a file object?
a. To create a new file
b. To move the file position to the specified location
c. To close a file
d. To write data to a file
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
162. In Python, what is a binary file?
a. A file that contains only binary data
b. A file that contains only text data
c. A file that cannot be opened
d. an empty 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”)
164. How do you read data from a binary file in Python?
a. Use the readline() method
b. Use the write() method
c. Use the read() method
d. Use the print() function
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()
166. How can you write data to a binary file in Python?
a. Use the read() method
b. Use the write() method
c. Use the readline() method
d. Use the print() function
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”
168. How can you close a binary file in Python?
a. file.close() c. file.exit()
b. file.shutdown() d. file.end()
169. How can you read a specific number of bytes from a binary file in
Python?
a. file.read(10)
b. file.readline(10)
c. file.readbyte(10)
d. file.read(10, “binary”)
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”)
172. What is the purpose of the readline() method when working
with binary files in Python?
a. To read a line of text from the file
b. To read a line of binary data from the file
c. To close the file
d. To write data to the file
173. How do you open a binary file for writing in Python?
a. file = open(“file.txt”, “r”)
b. file = open(“file.txt”, “wb”)
c. file = open(“file.txt”, “w”)
d. file = open(“file.txt”, “rb”)
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
175. What is the purpose of the mode attribute of a file object in
Python?
a. It stores the file’s content
b. It stores the file’s name
c. It stores the file’s size
d. It stores the file’s open mode
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
186. What module can you use to handle command-line arguments in
Python?
a. os
b. sys
c. argparse
d. commands
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
189. What is the primary purpose of using command line arguments in
file handling with Python?
a. To complicate the code
b. To simplify the code
c. To eliminate the need for file paths
d. To make the code more readable
190. What is the purpose of using the argparse module when
working with command line arguments?
a. To create a user interface for the script
b. To define environment variables
c. To parse and handle command line arguments
d. To execute 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
193. The pickle module deals with _________?
a. text file
b. binary file
c. both text and binary file
d. none of the above
194. Which of the following method(s) provided by pickle module:
a. dump()
b. load()
c. both dump() and load()
d. none of the above
195. What is the primary purpose of the pickle module in Python?
a. To create compressed files
b. To work with JSON data
c. To serialize and deserialize Python objects
d. To read and write text files
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
198. Which function in the pickle module is used to deserialize and
load Python objects from a file?
a. pickle.read() c. pickle.parse()
b. pickle.load() d. pickle.unpack()
199. What is the purpose of the fileinput module in Python?
a. To read binary files
b. To work with text files
c. To handle input from the command line
d. To read and write compressed files
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()
201. In Python, what is the purpose of the gzip module?
a. To read text files
b. To work with JSON data
c. To compress and decompress files
d. To serialize Python objects
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”)
204. What is the primary purpose of the bz2 module in Python?
a. To compress and decompress files
b. To work with JSON data
c. To read and write text files
d. To serialize Python objects
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”)
208. What is the purpose of Python’s os.walk() function?
a. To walk through a directory tree and list all directories and files
b. To create a new directory
c. To copy a file
d. To remove a directory
209. Which module in Python provides functions for searching files
using pattern matching?
a. os c. fnmatch
b. shutil d. glob
210. What is the primary purpose of the glob module in Python?
a. To read and write binary files
b. To search for files using wildcards and patterns
c. To create compressed files
d. To serialize Python objects
211. Using the glob module, which function is used to find all files and
directories that match a specified pattern in Python?
a. glob.list() c. glob.match()
b. glob.glob() d. glob.find()
212. In Python, what is the primary purpose of the
os.path.isfile() function?
a. To list all files in a directory
b. To check if a path is a file
c. To remove a file
d. To create a new file
213. What does the os.path.isdir() function in Python check for?
a. Whether a path is a directory
b. Whether a path is a file
c. Whether a path exists
d. Whether a path is a symbolic link
214. What is the purpose of the os.path.basename() function in
Python?
a. To get the directory name
b. To get the file’s extension
c. To get the absolute path of a file
d. To get the file’s name
215. What is the primary purpose of the os.path.getsize()
function in Python?
a. To get the creation time of a file
b. To get the size of a file in bytes
c. To get the last modification time of a file
d. To get the owner of a file
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
218. What is one advantage of file handling in Python?
a. Efficient data storage and retrieval
b. Increased CPU performance
c. Real-time data processing
d. Improved network connectivity
219. What is the disadvantage of file handling in Python?
a. Real-time data processing
b. Limited data storage capacity
c. Improved security
d. Reduced data accessibility
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
222. How can file handling be advantageous in data backup and
recovery?
a. It prevents data loss.
b. It is faster than other methods.
c. It provides real-time data recovery.
d. It ensures data security.
223. What is a potential disadvantage of file handling in Python when
dealing with large datasets?
a. Faster data retrieval
b. Increased memory usage
c. Better data organization
d. Improved data sharing
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
225. What is a common disadvantage of using files for data storage in
Python, particularly in multi-user environments?
a. Improved data sharing
b. Simultaneous data access issues
c. Real-time data updates
d. Reduced data corruption risk
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
228. How can file handling be advantageous in data privacy and
security scenarios?
a. By making data more accessible
b. By ensuring real-time data updates
c. By providing encryption options
d. By improving data sharing
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
231. What is a potential disadvantage of file handling in Python when
dealing with data in a distributed system?
a. Improved data sharing
b. Limited data consistency
c. Enhanced data security
d. Real-time data updates
232. How can file handling be advantageous for archiving historical
data in Python applications?
a. By reducing data storage space
b. By ensuring real-time data updates
c. By providing a long-term data storage solution
d. By improving data retrieval speed
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
234. How can file handling be advantageous for small-scale Python
applications with limited resources?
a. By ensuring data consistency
b. By providing real-time data processing capabilities
c. By reducing the need for a database server
d. By enhancing data security
235. What is a potential disadvantage of file handling in Python
compared to cloud storage?
a. Improved data security
b. Limited data accessibility
c. Enhanced data-sharing capabilities
d. Real-time data synchronization
236. How can file handling be advantageous for exchanging data
between different applications and platforms in Python?
a. By making data transfer more efficient
b. By preventing data sharing
c. By providing real-time data processing capabilities
d. By reducing data persistence
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
238. Which character is used as the directory separator in file paths in
Linux?
a. Backslash (\)
b. Forward slash (/)
c. Pipe (|)
d. Tilde (~)
239. In Windows, which character is used as the directory separator in
file paths?
a. Backslash (\)
b. Forward slash (/)
c. Pipe (|)
d. Tilde (~)
240. Which Python module provides a platform-independent way to
work with file paths and directories?
a. os c. pathlib
b. platform d. sys
241. In Linux, which command is used to change the current working
directory?
a. cd c. cwd
b. chdir d. change_dir
242. Which module in Python provides functions for working with file
and directory permissions in a platform-independent way?
a. os c. pathlib
b. platform d. permissions
243. In Linux, what is the command to change the permissions of a file
to read, write, and execute for the owner?
a. chmod 700 file.txt
b. chown owner=rwx file.txt
c. chgrp owner=rwx file.txt
d. chmod u=rwx file.txt
244. In Windows, what is the command to change the permissions of a
file to read, write, and execute for the owner?
a. chmod 700 file.txt
b. icacls file.txt /grant:rwx
c. cacls file.txt /rwx
d. grant-permission file.txt -rwx
245. Which Python module is commonly used to create and manage
symbolic links in Linux and Windows?
a. os c. symlink
b. pathlib d. link
246. What command is used in Linux to create a symbolic link from
source to target?
a. symlink source target
b. ln -s source target
c. link source target
d. ln source target
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
249. What is the purpose of a file object’s readlines() method in
Python?
a. Reads a single character from the file
b. Reads a single line from the file
c. Reads all lines from the file into a list
d. Closes the file
250. What will happen if you attempt to rename a file to a name
already in the same directory using the shutil.rename()
method?
a. The new file will overwrite the original file.
b. An error will be raised, and the file won’t be renamed.
c. The new file will be created with a different name.
d. Both files will coexist in the directory with the same name.
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
1 b 51 c 101 d 151 a 201 c
2 c 52 c 102 d 152 b 202 d
3 a 53 b 103 c 153 d 203 a
4 b 54 a 104 a 154 b 204 a
5 b 55 d 105 c 155 a 205 c
6 a 56 b 106 c 156 c 206 c
7 b 57 d 107 b 157 c 207 a
8 c 58 c 108 a 158 d 208 a
9 c 59 a 109 a 159 c 209 c
10 a 60 c 110 c 160 c 210 b
11 c 61 c 111 c 161 b 211 b
12 d 62 c 112 a 162 a 212 b
13 c 63 c 113 c 163 a 213 a
14 a 64 b 114 b 164 c 214 d
15 a 65 b 115 b 165 c 215 b
16 a 66 b 116 b 166 b 216 a
17 b 67 d 117 b 167 d 217 b
18 a 68 c 118 c 168 a 218 a
19 b 69 b 119 c 169 a 219 b
20 c 70 a 120 c 170 c 220 c
21 c 71 b 121 c 171 b 221 b
22 c 72 b 122 c 172 b 222 a
23 a 73 b 123 b 173 b 223 b
24 b 74 b 124 d 174 d 224 c
25 c 75 b 125 c 175 d 225 b
26 b 76 b 126 a 176 b 226 c
27 b 77 b 127 c 177 b 227 c
28 a 78 d 128 c 178 a 228 c
29 c 79 b 129 c 179 d 229 b
30 b 80 c 130 c 180 c 230 c
31 b 81 a 131 b 181 b 231 b
32 c 82 b 132 b 182 d 232 c
33 b 83 c 133 b 183 d 233 b
34 a 84 b 134 a 184 a 234 c
35 d 85 b 135 a 185 c 235 b
36 b 86 a 136 c 186 c 236 a
37 c 87 a 137 c 187 c 237 b
38 b 88 b 138 c 188 b 238 b
39 b 89 a 139 c 189 b 239 a
40 d 90 d 140 c 190 c 240 c
41 b 91 c 141 d 191 a 241 a
42 d 92 c 142 b 192 b 242 a
43 a 93 b 143 c 193 b 243 a
44 c 94 b 144 a 194 c 244 b
45 d 95 c 145 a 195 c 245 a
46 c 96 c 146 c 196 c 246 b
47 b 97 a 147 c 197 c 247 c
48 d 98 b 148 b 198 b 248 c
49 b 99 b 149 b 199 b 249 c
50 b 100 b 150 b 200 b 250 a
CHAPTER 11
Exception Handling
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.
Multiple choice questions
1. What does the term exception refer to in Python programming?
a. A syntax error in the code.
b. An event that disrupts the normal flow of a program’s execution.
c. A warning generated during runtime.
d. An event that terminates the program abruptly.
2. Which keyword is used to handle exceptions in Python?
a. handle
b. try
c. except
d. catch
3. What will happen if an exception is not handled in Python?
a. The program continues normally.
b. The program prints an error message and halts.
c. The program bypasses the exception.
d. The program retries the code block.
4. What is the purpose of the finally block in Python exception
handling?
a. To handle exceptions.
b. To ignore exceptions.
c. To execute code regardless of whether an exception occurred or
not.
d. To define a custom exception.
5. Which function in Python allows developers to manually raise
exceptions?
a. raise_exception() c. exception()
b. throw() d. raise
6. In Python, which type of error is raised when a program tries to
access a variable that is not defined?
a. SyntaxError c. ValueError
b. NameError d. TypeError
7. What is the primary purpose of the try block in Python exception
handling?
a. To handle exceptions.
b. To execute code that might generate exceptions.
c. To define custom exceptions.
d. To skip exceptions.
8. What will the following code output?
try:
num = 10 / 0
except ZeroDivisionError:
print("Division by zero error.")
a. Division by zero error.
b. ZeroDivisionError.
c. The code will not produce any output.
d. An exception will be raised, but not handled.
9. What will the else block in Python exception handling execute
when there are no exceptions raised in the try block?
a. It executes if any exception is caught.
b. It executes regardless of exceptions being raised.
c. It doesn’t execute.
d. It executes only when no exceptions are raised.
10. Which Python built-in function can be used to obtain information
about the last exception that occurred?
a. last_exception()
b. exception_info()
c. sys.exc_info()
d. get_last_exception()
11. What is the purpose of the assert statement in Python?
a. To handle exceptions.
b. To throw exceptions.
c. To define custom exceptions.
d. To verify the truth of an expression.
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.
15. In Python, what is the output of the following code?
try:
num = int('ten')
except ValueError:
print("ValueError occurred.")
finally:
print("Finally block executed.")
a. ValueError occurred.
b. Finally block executed.
c. ValueError occurred. Finally block executed.
d. The code will result in an unhandled exception.
16. What is the Python keyword used to catch all exceptions?
a. catch
b. except all
c. catch all
d. except
17. Which exception is raised if an undefined attribute of an object is
accessed in Python?
a. AttributeError
b. KeyError
c. TypeError
d. NameError
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__()
19. What is the purpose of the with statement in Python exception
handling?
a. To catch exceptions.
b. To handle multiple exceptions.
c. To ensure the correct use of resources and automatically close
opened files.
d. To define custom exceptions.
20. In Python, what is the purpose of the except block in exception
handling?
a. To execute code regardless of an exception.
b. To catch and handle exceptions.
c. To define custom exceptions.
d. To ignore exceptions.
21. Which statement is used to raise a specified exception in Python?
a. throw
b. raise
c. throw_exception
d. exception
22. What will the following code’s output?
try:
result = 10 / 0
except ZeroDivisionError:
print("ZeroDivisionError occurred.")
a. ZeroDivisionError occurred.
b. Division by zero error.
c. The code will not produce any output.
d. An unhandled exception will occur.
23. What does the finally block in Python’s exception handling
ensure?
a. Execution regardless of an exception.
b. To raise exceptions.
c. To handle exceptions.
d. To define custom exceptions.
24. Which method is used to manually raise exceptions in Python?
a. raise_exception() c. exception()
b. throw() d. raise
25. In Python, which type of error is raised when trying to access an
undefined variable?
a. NameError
b. KeyError
c. AttributeError
d. TypeError
26. What is the purpose of the assert statement in Python?
a. To define custom exceptions
b. To throw exceptions
c. To verify the truth of an expression
d. To handle exceptions
27. In Python, how can detailed exception information be obtained
after an exception is caught?
a. Using sys.error_info()
b. Using exception.info()
c. Using sys.exc_info()
d. Using get_exception_details()
28. What is the primary purpose of the else block in Python
exception handling?
a. To execute if any exception is caught.
b. To execute regardless of exceptions being raised.
c. To execute only when no exceptions are raised.
d. It doesn’t execute.
29. In Python, which type of exception catches every possible error?
a. Error
b. Exception
c. RuntimeError
d. AllError
30. Which function in Python retrieves the error message associated
with an exception?
a. message()
b. exception_info()
c. str()
d. __str__()
31. In Python, which statement can be used to catch exceptions for
multiple error types?
a. except All
b. except (TypeError, ValueError)
c. catch
d. exception
32. What will the following code output?
try:
value = int('ten')
except ValueError:
print("ValueError occurred.")
finally:
print("Finally block executed.")
a. ValueError occurred.
b. Finally block executed.
c. ValueError occurred. Finally block executed.
d. The code will result in an unhandled exception.
33. In Python, what is the purpose of the with statement in exception
handling?
a. To handle multiple exceptions.
b. To ensure proper use of resources and automatically close opened
files.
c. To catch all exceptions.
d. To define custom exceptions.
34. Which exception is raised when trying to access an attribute that
does not exist in an object in Python?
a. KeyError
b. AttributeError
c. ValueError
d. NameError
35. What is the purpose of the raise statement in Python?
a. To handle exceptions.
b. To define custom exceptions.
c. To catch exceptions.
d. To verify expressions.
36. In Python, if an exception is not handled, what will occur?
a. The program continues normally.
b. The program terminates, and an error message is displayed.
c. The program retries the code block.
d. The program prints a warning message.
37. Which keyword is used to handle exceptions for specific error
types in Python?
a. except c. handle
b. error d. catch
38. In Python, what is the primary purpose of utilizing multiple except
blocks in exception handling?
a. To handle only a specific type of exception.
b. To handle every possible exception.
c. To catch and handle multiple exceptions separately.
d. To ignore exceptions.
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.
40. How do multiple except blocks function in Python when an
exception occurs?
a. The first matching except block is executed.
b. All matching except blocks are executed.
c. The last matching except block is executed.
d. Random except block is executed.
41. In Python, when using multiple except blocks, what happens if an
exception type is not matched by any except block?
a. It causes a syntax error.
b. The code raises an unhandled exception.
c. The program continues execution without any output.
d. It prints an error message but continues execution.
42. What is the advantage of utilizing multiple except blocks over a
single except block in Python?
a. It simplifies the code structure.
b. It allows handling different exceptions in different ways.
c. It does not impact code readability.
d. It increases the chances of errors.
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.
44. What will happen if an exception is handled by multiple except
blocks in Python?
a. The program raises an error.
b. It is considered an invalid syntax.
c. Only the first matched except block is executed.
d. All matched except blocks are executed.
45. How do you define multiple except blocks in Python?
a. By separating exceptions with a comma.
b. By using a semicolon between exception types.
c. By nesting except blocks.
d. By defining each exception type separately.
46. In Python, what will the following code output?
try:
num = int('ten')
except ValueError:
print("ValueError occurred.")
except TypeError:
print("TypeError occurred.")
a. ValueError occurred.
b. TypeError occurred.
c. The code will result in an unhandled exception.
d. It will no/cm,cb k T produce any output.
47. What happens if a specific exception is handled by multiple
except blocks in Python?
a. The code raises an ambiguity error.
b. It is considered invalid.
c. The last matching except block is executed.
d. Only the first matching except block is executed.
48. How can multiple exceptions be handled by a single except block
in Python?
a. By using a wildcard symbol (*).
b. By specifying all exception types within parentheses.
c. By using a specific keyword ‘multiple’.
d. It’s not possible; each exception requires a separate except block.
49. In Python, how does the ordering of multiple except blocks
affect exception handling?
a. The order has no impact on exception handling.
b. The last except block defined has the highest priority.
c. The first except block defined has the highest priority.
d. It results in a syntax error.
50. What will happen if a specific exception is not handled by any
except block in Python?
a. The program prints a warning message.
b. The code continues execution without any output.
c. It raises an unhandled exception.
d. It results in an infinite loop.
51. How is the flow of exception handling affected by using multiple
except blocks in Python?
a. It is entirely determined by the order of the except blocks.
b. It has no impact on the flow.
c. The execution is random.
d. It’s controlled by the order of the try block.
52. In Python, if multiple except blocks are defined and an
exception occurs, which block will be executed?
a. The last except block defined.
b. All except blocks are executed simultaneously.
c. The first matching except block in order of definition.
d. It results in an error.
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.
54. In Python, if no exception type is specified, what kind of
exceptions will the except block catch?
a. All exceptions
b. SyntaxError only
c. AttributeError only
d. ValueError only
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.
56. What is the Python keyword used to define a catch-all except
block for unknown exceptions?
a. exception All c. catch All
b. except All d. except
57. In Python, what is the primary benefit of handling multiple
exceptions using a single except block?
a. Improved code readability
b. Simplified exception handling
c. Reducing the number of code lines
d. Handling various exceptions similarly
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
59. In Python, what happens if a specific exception is not caught by
the listed exceptions in a multiple except block?
a. It triggers an unhandled exception
b. The program prints a warning message
c. The program continues without any output
d. It results in a syntax error
60. How is the flow of exception handling affected by using multiple
exceptions in a single except block in Python?
a. It’s solely dependent on the exception ordering
b. The execution follows a random order
c. The code raises an ambiguity error
d. It has no impact on exception handling flow
61. What will happen if a specific exception is handled by a single
except block in Python?
a. The last matching except block is executed
b. Only the first matching except block is executed
c. All matching except blocks are executed
d. It triggers an unhandled exception
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
63. What happens if a specific exception is not matched by any listed
exceptions in a multiple except block in Python?
a. It results in a syntax error
b. It is considered invalid
c. It triggers an unhandled exception
d. The program continues execution without any output
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
67. In Python, if multiple exceptions are mentioned within a single
except block, how are they handled?
a. All listed exceptions are caught simultaneously
b. Each exception is handled by a separate except block
c. Only the first matching exception is caught
d. The last matching exception is caught
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
69. In Python, what happens if multiple exceptions are specified
within a single except block and an unlisted exception occurs?
a. The program raises an ambiguity error
b. The code continues execution without any output
c. The last exception type is handled
d. It triggers an unhandled exception
70. What happens if multiple exceptions are specified in a single
except block in Python, but the exception raised does not match
any listed exception types?
a. The last exception type is handled
b. The code raises an unhandled exception
c. Only the first matching exception is handled
d. It triggers a syntax error
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
73. In Python, if multiple exceptions are mentioned within a single
except block, how are they handled?
a. All listed exceptions are caught simultaneously
b. Each exception is handled by a separate except block
c. Only the first matching exception is caught
d. The last matching exception is caught
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
75. In Python, what is the primary role of the else clause in
exception handling?
a. To execute only when an exception is raised
b. To ignore exceptions and execute the code
c. To define custom exceptions
d. To execute when no exceptions occur in the try block
76. What happens if a try block contains an else clause and an
exception occurs in Python?
a. The else block is skipped
b. The else block is executed
c. The program raises an unhandled exception
d. The code results in a syntax error
77. What is the primary function of the else clause in Python’s
exception handling?
a. To catch and handle exceptions
b. To execute code regardless of an exception
c. To define custom exceptions
d. To execute if no exceptions are raised
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
79. What happens if the else block in Python’s exception handling
contains code that raises an exception?
a. It results in an unhandled exception
b. The except block handles the raised exception
c. The program terminates without any output
d. The else block is skipped
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
81. What does the else clause ensure in Python’s exception
handling?
a. To handle any raised exception
b. To execute regardless of an exception
c. To define custom exceptions
d. To run code only if no exceptions are raised
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
83. What is the behavior of the else clause in Python’s exception
handling?
a. It always executes, irrespective of an exception
b. It only runs if exceptions occur
c. It executes when no exceptions are raised
d. It runs before the try block
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
85. What is the primary function of the else clause in Python’s
exception handling?
a. To catch and handle exceptions
b. To execute code regardless of an exception
c. To define custom exceptions
d. To execute when no exceptions are raised
86. What is the purpose of raising exceptions in Python?
a. To suppress errors in the code
b. To handle errors and continue code execution
c. To create and trigger errors deliberately
d. To avoid encountering errors in code
87. How is an exception raised explicitly in Python?
a. Using the raise statement
b. Employing the try block
c. Defining the exception in a function
d. Applying the assert keyword
88. In Python, which statement is used to raise a custom exception?
a. throw c. trigger
b. raise d. assert
89. What is the role of the raise statement in Python?
a. To catch exceptions
b. To suppress errors
c. To terminate the program
d. To generate and raise exceptions
90. How is a custom exception raised in Python?
a. Using the catch statement
b. Employing the raise statement with a specified exception
c. Defining a new exception within the code
d. Utilizing the try block
91. What happens if an exception is raised but not handled in Python?
a. The code executes the finally block
b. The program halts and terminates
c. The code retries the exception block
d. It leads to syntax errors
92. In Python, what is the primary function of raising exceptions?
a. To handle errors and continue execution
b. To mask the occurrence of errors
c. To bypass error handling mechanisms
d. To signal and deal with errors
93. What is the Python keyword used to raise an exception manually?
a. throw c. raise
b. except d. trigger
94. What is the primary purpose of using the raise statement in
Python?
a. To ignore exceptions
b. To define custom exceptions
c. To handle errors gracefully
d. To deliberately generate exceptions
95. How can custom exceptions be raised in Python?
a. By using the assert statement
b. Only within the try block
c. Using the raise statement with a defined exception
d. By incorporating the catch block
96. What occurs when an exception is raised in Python and is not
caught?
a. The program continues without any output
b. It results in an unhandled exception
c. The code reverts to the finally block
d. It raises a syntax error
97. What statement is used to create and raise custom exceptions in
Python?
a. throw c. generate
b. create d. raise
98. What is the primary function of raising exceptions in Python?
a. To halt the program execution
b. To handle errors and continue code execution
c. To suppress errors in the code
d. To terminate the program
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
101. How can a specific exception be raised in Python?
a. Using the throw keyword
b. Employing the assert statement
c. By manually defining exceptions
d. Using the raise statement with the specified exception
102. What occurs if an exception is raised in Python but not explicitly
handled?
a. It triggers the except block
b. The code proceeds to the finally block
c. It results in an unhandled exception
d. The program stops and prints an error message
103. How can an exception be deliberately triggered in Python?
a. By creating a try block without an except block
b. Using the raise statement with the specified exception
c. By ignoring error conditions in the code
d. Through the assert statement
104. In Python, what is the primary role of the raise statement?
a. To ignore exceptions
b. To handle errors gracefully
c. To define custom exceptions
d. To generate and raise exceptions
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
106. In Python, what is the purpose of handling exceptions within
functions?
a. To suppress all exceptions raised within the function
b. To prevent the function from raising any exceptions
c. To handle errors or exceptions that occur during function
execution
d. To avoid executing the function entirely
107. How can exceptions be handled within a function in Python?
a. Only by using a try block inside the function
b. Exclusively through the except block in the function
c. By encapsulating the function with try and except blocks
d. Exceptions can’t be handled within functions
108. What is the primary function of handling exceptions in functions
in Python?
a. To terminate the function immediately
b. To ignore all exceptions raised in the function
c. To allow the function to continue execution despite exceptions
d. To catch and deal with exceptions that occur during function
execution
109. How are exceptions typically handled within a Python function?
a. By enclosing the entire function in an except block
b. Using a try block followed by an except block within the function
c. Solely relying on the function’s return value
d. Exceptions can’t be handled within functions
110. In Python, what happens if an exception is raised within a function
and not handled?
a. The function continues execution as if no exception occurred
b. The program terminates immediately
c. The exception is suppressed by default
d. The function skips the current line and proceeds to the next
111. How can a function’s ability to raise exceptions be managed in
Python?
a. By avoiding all risky operations within the function
b. By using if statements to prevent exceptions
c. By including error checks and handling mechanisms within the
function
d. Functions cannot raise exceptions in Python
112. What is the advantage of handling exceptions within functions in
Python?
a. Functions automatically suppress all raised exceptions
b. It simplifies error handling mechanisms in the code
c. Functions become immune to exceptions once defined
d. It adds complexity to the overall program
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
115. What is the effect of handling exceptions within a function in
Python?
a. It suppresses all exceptions raised in the function
b. It enables the function to continue execution despite exceptions
c. It avoids the function from raising any exceptions
d. It halts the function’s execution immediately
116. In Python, what is the primary reason for handling exceptions
within functions?
a. To prevent exceptions from occurring
b. To handle errors or exceptions during function execution
c. To terminate the function abruptly
d. Functions are immune to exceptions by default
117. How are exceptions commonly managed within a function in
Python?
a. Using the except block alone in the function
b. Employing a try block with an associated except block in the
function
c. Functions can’t contain error-handling mechanisms
d. Functions automatically suppress exceptions
118. What happens if an exception occurs within a function, and it is
not caught or handled?
a. The function reverts to the previous line of code
b. The function continues execution normally
c. It triggers an unhandled exception and halts the function
d. Exceptions are automatically suppressed by the function
119. How can exceptions be managed within a function in Python?
a. By solely relying on the finally block
b. Functions inherently handle all exceptions raised within them
c. By utilizing a combination of try and except blocks
d. By avoiding any code that might raise exceptions within the
function
120. What is the impact of handling exceptions within functions on the
code’s error management in Python?
a. It completely avoids error handling mechanisms
b. It complicates error management in the code
c. It simplifies error management by concentrating it within
functions
d. Error handling within functions has no influence on code error
management
121. What is the primary function of the except block within a
function in Python?
a. To handle exceptions that occur during function execution
b. To suppress all raised exceptions in the function
c. To define the function’s return value in case of an exception
d. Functions do not contain except blocks
122. How does handling exceptions within functions affect program
execution in Python?
a. It allows the function to proceed without any interruption
b. It suppresses all exceptions that may occur within the function
c. It terminates the entire program immediately
d. It facilitates the program’s resilience against exceptions
123. What happens if an exception is raised within a function and
handled by an except block in Python?
a. The function halts and terminates abruptly
b. The exception is ignored, and the function continues
c. The function’s execution is unaffected by the exception
d. It triggers an unhandled exception within the function
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
126. What is the specific built-in exception raised when an unsupported
operation is performed?
a. UnsupportedError
b. NotSupportedError
c. NotImplementedError
d. OperationError
127. Which built-in exception in Python is raised when an arithmetic
operation encounters an error?
a. ArithmeticError
b. MathError
c. CalculationError
d. NumericError
128. What built-in exception is raised in Python when an object or
value is of the wrong type?
a. TypeError
b. ValueError
c. IncorrectTypeError
d. ObjectError
129. What is the specific built-in exception raised when an operation is
performed on an empty sequence?
a. EmptySequenceError
b. NoElementError
c. IndexError
d. LookupError
130. Which built-in exception is raised when an interpreter detects a
cycle in the sequence of references?
a. ReferenceError
b. CircularReferenceError
c. LoopError
d. CyclicError
131. What built-in exception is raised when an operation or function is
attempted that is not implemented?
a. NotImplementedError
b. NotSupportedError
c. UnavailableError
d. UnsupportedError
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
139. Which built-in exception is raised when an iterable object has no
further items available?
a. EndIterationError
b. StopIteration
c. NoMoreElementsError
d. NoElementError
140. What is the specific built-in exception raised when an operation
exceeds the limit for a built-in data type?
a. RangeError c. MemoryError
b. LimitError d. OverflowError
141. Which built-in exception in Python is raised when an operation is
performed on an empty slice?
a. EmptySliceError c. IndexError
b. NoSliceError d. SliceError
142. What is the specific built-in exception raised when the key does
not exist in the specified mapping or dictionary?
a. NoKeyError
b. KeyNotFoundError
c. MissingKeyError
d. KeyError
143. What is the specific built-in exception raised when an operation or
function is attempted with an argument of the correct type but
inappropriate value?
a. ValueError
b. TypeError
c. InappropriateValueError
d. ArgumentValueError
144. Which built-in exception is raised when a sequence subscript is out
of range?
a. RangeError
b. IndexError
c. SubscriptError
d. OutOfBoundsError
145. What is the specific built-in exception raised when a specific
attribute or method is not found in an object?
a. AttributeError
b. MethodError
c. MissingAttributeError
d. AttributeNotFoundError
146. Which built-in exception is raised when an operation results in a
division by zero?
a. ZeroDivisionError
b. ArithmeticError
c. DivisionError
d. MathError
147. What is the specific built-in exception raised when an invalid
conversion to an integer is attempted?
a. InvalidConversionError
b. TypeConversionError
c. ValueError
d. IntConversionError
148. Which built-in exception in Python is raised when an attribute
reference or assignment fails?
a. AccessError
b. AttributeError
c. AttributeAccessError
d. ReferenceError
149. What is the specific built-in exception raised when an argument is
of the correct type but has an invalid value?
a. InvalidArgumentError
b. ValueError
c. TypeError
d. BadValueError
150. Which built-in exception is raised when an object of an
inappropriate type is passed to a function?
a. InvalidTypeError
b. TypeMismatchError
c. TypeError
d. IncompatibleTypeError
151. What is the specific built-in exception raised when an assertion
fails?
a. AssertError
b. AssertionError
c. AssertionFailure
d. ValidationError
152. Which built-in exception in Python is raised when a name
referenced in the local or global scope is not found?
a. NameError
b. ReferenceError
c. IdentifierError
d. ScopeError
153. What is the specific built-in exception raised when an operation is
attempted with an object of inappropriate type?
a. TypeMismatchError
b. IncompatibleTypeError
c. TypeError
d. MismatchError
154. Which built-in exception is raised when an operation on a file is
not valid?
a. FileError
b. IOError
c. InvalidFileError
d. BadFileOperationError
155. What is the specific built-in exception raised when an invalid
syntax is encountered?
a. SyntaxError
b. ParsingError
c. InvalidSyntaxError
d. SyntaxParsingError
156. Which built-in exception in Python is raised when an invalid
operation for a given data type is attempted?
a. OperationError
b. InvalidOperationError
c. TypeError
d. DataError
157. What is the specific built-in exception raised when an I/O
operation fails for a system-related reason?
a. SystemIOError
b. IOFailureError
c. SystemError
d. IOPermissionError
158. Which built-in exception is raised when an illegal memory access
is attempted?
a. MemoryError
b. MemoryAccessError
c. IllegalMemoryError
d. OutOfMemoryError
159. What is the specific built-in exception raised when the maximum
recursion depth is exceeded?
a. MaxRecursionError
b. RecursionError
c. DepthError
d. RecursionDepthError
160. Which built-in exception in Python is raised when a key in the
dictionary is not found?
a. KeyNotFoundError
b. MissingKeyError
c. NotFoundException
d. KeyError
161. What is a user-defined exception in Python?
a. Exceptions defined by the Python interpreter
b. Exceptions generated by the user’s input
c. Custom exceptions created by Python developers
d. Built-in exceptions provided by Python libraries
162. Which statement best describes the purpose of user-defined
exceptions in Python?
a. To suppress built-in exceptions
b. To complicate the error handling process
c. To provide a way to define and raise custom exceptions
d. To replace standard Python exceptions
163. How are user-defined exceptions created in Python?
a. Using built-in exceptions as templates
b. Solely through the try block
c. By importing external libraries
d. By creating a new class that inherits from the Exception class
164. What is the primary function of user-defined exceptions in
Python?
a. To override all standard exceptions
b. To provide an alternative for error handling
c. To simplify error handling mechanisms
d. To create and manage specific error cases
165. When creating a user-defined exception in Python, what is the
recommended inheritance for the custom exception class?
a. Inheriting from the list class
b. Inheriting from the BaseException class
c. Inheriting from the StandardError class
d. Inheriting from the Exception class
166. What is the benefit of using user-defined exceptions in Python?
a. To suppress errors completely
b. To handle only built-in exceptions
c. To centralize error handling for specific cases
d. To avoid error handling altogether
167. How are user-defined exceptions raised in Python?
a. Using the catch statement
b. By explicitly raising the custom exception using the raise
statement
c. Only through the try block
d. By directly calling the exception class
168. What should be considered when creating custom exceptions in
Python?
a. Overriding built-in exceptions
b. Addressing specific and unique error scenarios
c. Replacing all standard Python exceptions
d. Ignoring error cases altogether
169. What is the primary advantage of using user-defined exceptions in
Python?
a. Simplifying error handling mechanisms
b. Avoiding the need for any exception handling
c. Creating confusion in error management
d. Overriding built-in Python exceptions
170. How are user-defined exceptions handled in Python?
a. Exclusively within the finally block
b. By applying the except block
c. Automatically without specific handling
d. Only with the try block
171. What is the recommended approach to naming user-defined
exceptions in Python?
a. Using any generic name for clear identification
b. Following the convention of descriptive and meaningful names
c. Avoiding names relevant to the error context
d. Utilizing only single-character names for simplicity
172. What makes user-defined exceptions advantageous in Python?
a. They hinder the error handling process
b. They create more complexity in handling errors
c. They enable developers to handle specific error cases
d. They replace all built-in exceptions
173. How do user-defined exceptions aid in code development in
Python?
a. By adding unnecessary complexity to the code
b. By replacing all existing exceptions with custom ones
c. By offering the ability to tailor error handling to specific
situations
d. By bypassing the need for any error management
174. What is the typical approach to handling user-defined exceptions
in Python?
a. Automatically handled by the Python interpreter
b. Ignoring these exceptions for better code performance
c. Employing the try and except blocks as with built-in exceptions
d. Managing these only within the finally block
175. How does using user-defined exceptions enhance code readability
in Python?
a. By obfuscating the code structure
b. By introducing irrelevant error messages
c. By providing context-specific error handling
d. By avoiding all error descriptions
176. How do user-defined exceptions contribute to effective error
handling in Python?
a. By exclusively managing common errors
b. By introducing a universal error-handling mechanism
c. By tailoring error handling to unique error cases
d. By bypassing the need for error management
177. What is the primary purpose of using user-defined exceptions in
Python?
a. To suppress all error messages
b. To override built-in exceptions
c. To create specialized error handling
d. To eliminate the need for exception handling
178. How do user-defined exceptions improve the error-handling
process in Python?
a. By complicating and slowing down error management
b. By avoiding specific error cases
c. By allowing tailored handling of distinct error scenarios
d. By overriding all built-in exceptions
179. What is the primary advantage of employing user-defined
exceptions in Python?
a. To simplify the error-handling process
b. To replace all built-in exceptions
c. To hinder the error management mechanisms
d. To introduce generic error descriptions
180. What is the purpose of creating user-defined exceptions in
Python?
a. To introduce generic error messages
b. To suppress all built-in exceptions
c. To provide custom error handling for specific scenarios
d. To override the interpreter’s error management system
181. How are user-defined exceptions differentiated from built-in
exceptions in Python?
a. They do not require any handling procedures
b. They use predefined error messages
c. They offer specialized error management
d. They are automatically raised without explicit statements
182. What is a primary consideration when designing and
implementing user-defined exceptions in Python?
a. Creating ambiguous and non-descriptive exceptions
b. Using generic exception messages for all cases
c. Defining specific and meaningful exceptions
d. Avoiding any error-handling mechanisms
183. What is the significant advantage of employing user-defined
exceptions in Python?
a. They complicate error management processes
b. They offer no additional benefits compared to built-in exceptions
c. They enable developers to handle unique error cases
d. They replace all standard Python exceptions
184. How do user-defined exceptions enhance the error-handling
process in Python?
a. By making error handling generic and unspecific
b. By hindering the code readability
c. By tailoring error handling for distinct scenarios
d. By suppressing all errors raised in the code
185. What is the typical approach to handling user-defined exceptions
in Python?
a. Ignoring these exceptions for a streamlined code
b. Automatically handled by the interpreter
c. Employing the try and except blocks as with built-in exceptions
d. Managing these only within the finally block
186. How do user-defined exceptions contribute to effective error
handling in Python?
a. By exclusively handling common errors
b. By introducing a universal error-handling mechanism
c. By tailoring error handling to unique error cases
d. By bypassing the need for error management
187. What is the typical approach to naming user-defined exceptions in
Python?
a. Using any generic name for clear identification
b. Following the convention of descriptive and meaningful names
c. Avoiding names relevant to the error context
d. Utilizing only single-character names for simplicity
188. What is the primary function of using user-defined exceptions in
Python?
a. To suppress all error messages
b. To replace built-in exceptions
c. To create and manage specific error cases
d. To avoid error handling mechanisms
189. How do user-defined exceptions aid in effective error handling in
Python?
a. By exclusively handling common errors
b. By introducing a universal error-handling mechanism
c. By tailoring error handling to unique error cases
d. By bypassing the need for error management
190. In Python, within a try block, what follows the finally
block?
a. catch block
b. Another try block
c. else block
d. except block
191. What does the finally block ensure in Python?
a. It handles the exceptions raised in the try block
b. It executes irrespective of whether an exception occurs or not
c. It halts the program’s execution immediately
d. It is optional and can be omitted
192. Which statement best describes the functionality of the finally
block in Python?
a. It is used to suppress all exceptions raised in the try block
b. It always executes, whether an exception is raised or not
c. It replaces the role of the try block
d. It functions as the primary exception handler
193. What is the primary role of the finally block in Python’s
exception handling?
a. To replace the try block entirely
b. To execute code regardless of an exception occurrence
c. To exclusively manage exceptions
d. To terminate the program immediately
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
197. What is the primary role of the finally block in Python’s
exception handling structure?
a. To replace the try block
b. To handle only specific exceptions
c. To execute cleanup code whether an exception is raised or not
d. To halt the program’s execution
198. How does the finally block contribute to better code
management in Python?
a. By handling all exceptions in the program
b. By suppressing exceptions in the try block
c. By executing necessary cleanup code under all circumstances
d. By replacing the need for the try block entirely
199. What is the primary purpose of the finally block in Python’s
exception handling?
a. To execute cleanup code under any situation
b. To terminate the program immediately
c. To exclusively handle exceptions
d. To suppress all exceptions raised in the try block
200. In Python, what is the execution sequence involving the finally
block in the exception handling structure?
a. It is executed only when no exception occurs in the try block
b. It always executes, whether an exception occurs or not
c. It executes before the try block
d. It executes only after handling the exceptions in the catch 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
203. In Python, what is the fundamental function of the finally
block in the exception handling structure?
a. To replace the try block
b. To exclusively manage exceptions
c. To ensure the execution of specified code, whether an exception
occurs or not
d. To suppress all exceptions raised in 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
205. How does the finally block contribute to better error
management in Python?
a. By exclusively managing errors in the try block
b. By terminating the program’s execution immediately
c. By executing necessary cleanup code under all circumstances
d. By suppressing all exceptions in the try block
206. What is the primary purpose of pre-defined clean-up actions in
Python?
a. To handle exceptions efficiently
b. To execute specific code when an exception occurs
c. To ensure certain actions are taken, regardless of exceptions
d. To replace the need for error handling mechanisms
207. How does Python support pre-defined clean-up actions?
a. Through the cleanup keyword
b. By using a separate cleanup function
c. Using the finally block after a try block
d. Solely through the except block
208. What makes the pre-defined clean-up action important in
Python’s exception handling?
a. It prevents exceptions from occurring
b. It helps to ignore exceptions
c. It ensures necessary actions are executed, regardless of
exceptions
d. It replaces the need for try and except blocks
209. Which Python construct is used for executing pre-defined clean-up
actions?
a. finalize
b. end
c. complete
d. finally
210. How is the finally block utilized for pre-defined clean-up in
Python?
a. To exclusively handle exceptions
b. To suppress exceptions raised in the try block
c. To execute cleanup code regardless of exceptions
d. To terminate the program immediately
211. What is the significance of the finally block for pre-defined
clean-up in Python?
a. It completely halts the program’s execution
b. It is optional and can be omitted
c. It ensures the execution of specific code, irrespective of
exceptions
d. It replaces the need for 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
213. What differentiates pre-defined clean-up actions in Python from
handling exceptions?
a. It simplifies error management processes
b. It replaces the need for the try block
c. It specifically ignores all exceptions
d. It ensures certain actions are performed regardless of exceptions
214. How does the finally block contribute to effective error
management in Python?
a. By exclusively handling specific exceptions
b. By replacing the need for error handling mechanisms
c. By executing cleanup code, irrespective of exceptions
d. By terminating the program’s execution immediately
215. What is the primary advantage of employing pre-defined clean-up
actions in Python?
a. To suppress all exceptions in the try block
b. To completely halt the program’s execution
c. To ensure specific actions are taken, irrespective of exceptions
d. To ignore the need for exception handling
216. How does the finally block support 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
217. What is the primary function of the finally block in Python’s
exception handling?
a. To execute cleanup code only in case of specific exceptions
b. To ensure specific actions are taken, irrespective of exceptions
c. To suppress all exceptions in the try block
d. To handle only particular exceptions raised in the code
218. What does the finally block guarantee in Python’s exception
handling?
a. It is executed only when no exceptions occur in the code
b. It exclusively handles all exceptions raised in the try block
c. It executes cleanup code, whether an exception occurs or not
d. It is an optional block and can be omitted
219. How does the finally block contribute to better error
management in Python?
a. By exclusively handling specific errors
b. By terminating the program’s execution immediately
c. By executing necessary cleanup code under all circumstances
d. By suppressing all exceptions in the try block
220. What is the primary advantage of employing pre-defined clean-up
actions in Python?
a. To replace all exceptions with custom ones
b. To completely halt the program’s execution
c. To ensure specific actions are performed, irrespective of
exceptions
d. To ignore the need for exception handling
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
223. What makes the finally block significant in Python’s exception
handling?
a. It suppresses all exceptions in the try block
b. It completely halts the program’s execution
c. It ensures specific actions are performed, irrespective of
exceptions
d. It replaces the need for error handling mechanisms
224. Which block lets you test a block of code for errors?
a. try
b. except
c. finally
d. None of the above
225. What will be output for the following code:
try:
print(x)
except:
print(""An exception occurred"")
a. x
b. An exception occurred
c. Error
d. None of the above
226. What will be output for the following code:
try:
f = open(""demofile.txt"")
f.write(""Lorum Ipsum"")
except:
print(""Something went wrong when writing to
the file"")
finally:
f.close()
a. demofile.txt
b. Lorum Ipsum
c. Garbage value
d. Something went wrong when writing to the file
227. Which exception raised when a calculation exceeds maximum limit
for a numeric type?
a. StandardError
b. ArithmeticError
c. OverflowError
d. FloatingPointError
228. How many except statements can a try-except block have?
a. 0
b. 1
c. more than one
d. more than zero
229. How many except statements can a try-except block have?
a. zero
b. one
c. more than one
d. more than zero
230. Is the following Python code valid:
try:
# Do something
except:
# Do something
else:
# Do something
a. no, there is no such thing as else
b. no, else cannot be used with except
c. no, else must come before except
d. yes
231. What will be the output of the following Python code:
def foo():
try:
print(1)
finally:
print(2)
foo()
a. 1 2
b. 1
c. 2
d. none of the mentioned
232. What happens when ‘1’ == 1 is executed?
a. we get a True
b. we get a False
c. an TypeError occurs
d. a ValueError occurs
233. What type of error will be raised when the imported module is not
found?
a. ImportError
b. ModuleNotFoundError
c. AttributeError
d. NameError
234. Which of the following exception is raised when a built-in method
or operation receives an argument that has the right data type but
is mismatched or has inappropriate values?
a. Syntax Error
b. IOError
c. OverFlow Error
d. Value Error
235. It is raised when the end of file condition is reached without
reading any data by input():
a. Import Error
b. EOF Error
c. Index Error
d. Type Error
236. It is raised when the result of a calculation exceeds the maximum
limit for the numeric data type:
a. OverFlow Error
b. Indentation Error
c. Keyboard Interrupt
d. Syntax Error
237. What will be the output of the following Python code:
x=10
y=8
assert x>y, 'X too small'
a. Assertion Error
b. 10 8
c. No output
d. 108
238. What will be the output of the following Python code:
lst = [1, 2, 3]
lst[3]
a. NameError
b. ValueError
c. IndexError
d. TypeError
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
240. What will be the output of the following Python code:
int('65.43')
a. ImportError
b. ValueError
c. TypeError
d. NameError
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 b 51 a 101 d 151 b 201 c
2 c 52 c 102 c 152 a 202 c
3 b 53 c 103 b 153 c 203 c
4 c 54 a 104 d 154 b 204 b
5 d 55 b 105 c 155 a 205 c
6 b 56 b 106 c 156 a 206 c
7 b 57 d 107 c 157 c 207 c
8 a 58 d 108 d 158 a 208 c
9 d 59 a 109 b 159 b 209 d
10 c 60 a 110 b 160 d 210 c
11 d 61 b 111 c 161 c 211 c
12 a 62 b 112 b 162 c 212 d
13 d 63 c 113 c 163 d 213 d
14 a 64 c 114 b 164 d 214 c
15 c 65 a 115 b 165 d 215 c
16 d 66 c 116 b 166 c 216 c
17 a 67 c 117 b 167 b 217 b
18 c 68 c 118 c 168 b 218 c
19 c 69 d 119 c 169 a 219 c
20 b 70 b 120 c 170 b 220 c
21 b 71 b 121 a 171 b 221 c
22 a 72 b 122 a 172 c 222 c
23 a 73 c 123 b 173 c 223 c
24 d 74 b 124 a 174 c 224 a
25 a 75 d 125 a 175 c 225 b
26 c 76 a 126 c 176 c 226 d
27 c 77 d 127 a 177 c 227 c
28 c 78 d 128 a 178 c 228 d
29 b 79 a 129 c 179 a 229 d
30 c 80 d 130 b 180 c 230 d
31 b 81 d 131 a 181 c 231 a
32 c 82 d 132 a 182 c 232 b
33 b 83 c 133 b 183 c 233 a
34 b 84 b 134 b 184 c 234 d
35 b 85 d 135 c 185 c 235 b
36 b 86 c 136 b 186 c 236 a
37 a 87 a 137 b 187 b 237 c
38 c 88 b 138 c 188 c 238 c
39 d 89 d 139 b 189 c 239 d
40 a 90 b 140 d 190 b 240 b
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
50 c 100 d 150 c 200 b
CHAPTER 12
Modules
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.
2. Which keyword is used to import a module in Python?
a. using c. include
b. import d. require
3. Which statement is true about Python modules?
a. They can only be written in C++.
b. T hey can be executed independently.
c. They can only contain functions and no variables.
d. They are not allowed in object-oriented programming.
4. What is the purpose of the __init__.py file in a module?
a. It defines the main function of the module.
b. It serves as the entry point for executing the module.
c. It indicates that the directory is a Python package.
d. It contains the documentation for the module.
5. How can you access a function from a module in Python?
a. By using the module keyword followed by the function name.
b. By importing the module and then calling the function directly.
c. By importing the module and then using the import() function.
d. By importing the module and then accessing the function using
dot notation.
6. Which function is used to find all the attributes and methods of a
module in Python?
a. module_attributes()
b. dir()
c. list_attributes()
d. module_methods()
7. Which of the following statement is true about the random module
in Python?
a. It is used for performing mathematical operations.
b. It is used for generating random numbers.
c. It is used for string manipulation.
d. It is used for file input/output operations.
8. What is the purpose of the math 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 working with strings.
d. It provides functionalities for reading and writing files.
9. What is the use of the os module in Python?
a. It is used for creating graphical user interfaces.
b. It is used for networking operations.
c. It is used for file and directory manipulation.
d. It is used for database operations.
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.
12. Which module is used for performing regular expression
operations in Python?
a. re c. regular
b. regex d. regexp
13. What is the purpose of the sys module in Python?
a. It provides functionalities for working with the system’s
operating system.
b. It provides functionalities for creating graphical user interfaces.
c. It provides functionalities for performing mathematical
operations.
d. It provides functionalities for networking operations.
14. Which module is used for sending emails using Python?
a. email c. smtp
b. smtplib d. mail
15. What is the purpose of the random module’s seed() function in
Python?
a. It generates a random number.
b. It sets the seed for the random number generator.
c. It returns the current time in seconds.
d. It returns a random element from a list.
16. How can you install a module in Python using pip?
a. Run the command “pip install module_name” in the terminal.
b. Download the module file and copy it to the Python installation
directory.
c. Run the command “python install module_name” in the terminal.
d. Add the module’s folder to the system’s PATH variable.
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.
19. How can you create your own module in Python?
a. Create a text file with Python code and save it with a .py
extension.
b. Create a new folder and include the Python code files in it.
c. Write the Python code directly in a Jupyter Notebook cell.
d. Use the import keyword to define a new module in an existing
Python file.
20. Which module is used for working with SQLite databases in
Python?
a. sqlite3 c. sql
b. db d. pysqlite
21. How can you generate random numbers within a specific range
using the random module in Python?
a. By using the function random_number(start, end)
b. By using the function generate_random(start, end)
c. By using the function randint(start, end)
d. By using the function random(start, end)
22. What is the purpose of the time module in Python?
a. It provides functionalities for working with dates and times.
b. It provides functionalities for reading and writing files.
c. It provides functionalities for performing mathematical
operations.
d. It provides functionalities for creating graphical user interfaces.
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.
25. How can you access the command-line arguments in Python?
a. By using the sys module’s argv attribute.
b. By importing the argparse module and using its functions.
c. By using the os module’s argv attribute.
d. By importing the getopt module and using its functions.
26. Which module is used for working with CSV files in Python?
a. csv
b. pycsv
c. excelcsv
d. filecsv
27. What is the use of the subprocess 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 executing system commands.
d. It provides functionalities for networking operations.
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
30. What is the purpose of the platform module in Python?
a. It provides functionalities for working with dates and times.
b. It provides functionalities for performing mathematical
operations.
c. It provides functionalities for interacting with the operating
system.
d. It provides functionalities for creating graphical user interfaces.
31. Which module is used for working with images in Python?
a. PIL
b. img
c. picture
d. image
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
35. What is the purpose of the shutil module in Python?
a. It provides functionalities for working with dates and times.
b. It provides functionalities for performing mathematical
operations.
c. It provides functionalities for file and directory operations.
d. It provides functionalities for networking operations.
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
37. What is the purpose of the pickle 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 serializing and deserializing Python
objects.
d. It provides functionalities for networking operations.
38. Which module is used for working with HTTP requests in Python?
a. requests
b. http
c. httprequest
d. urllib
39. What is the use of the calendar module in Python?
a. It provides functionalities for working with dates and times.
b. It provides functionalities for writing and reading files.
c. It provides functionalities for performing mathematical
operations.
d. It provides functionalities for handling calendar data.
40. How can you generate a random floating-point number between 0
and 1 using the random module in Python?
a. By using the function random_float()
b. By using the function generate_float()
c. By using the function random()
d. By using the function random_number(0, 1)
41. Which module is used for working with audio files in Python?
a. pyaudio
b. audiofile
c. sound
d. wave
42. What is the purpose of the itertools module in Python?
a. It provides functionalities for creating graphical user interfaces.
b. It provides functionalities for generating iterators for efficient
looping.
c. It provides functionalities for performing mathematical
operations.
d. It provides functionalities for networking operations.
43. How can you check if a module is installed in Python?
a. By using the import keyword and checking for any import errors.
b. By running the command “pip list” in the terminal and checking
the installed packages.
c. By using the sys module’s is_installed() function.
d. By importing the module and checking if its version is available.
44. What is the use of the functools 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 handling and manipulating
functions.
d. It provides functionalities for networking operations.
45. Which module is used for working with MongoDB databases in
Python?
a. pymongo
b. mongodatabase
c. mgo
d. mongolib
46. What is the purpose of the pprint 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 pretty-printing Python objects.
d. It provides functionalities for networking operations.
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.
48. Which module is used for working with regular expressions in
Python?
a. re c. regular
b. regex d. regexp
49. What is the use of the hashlib 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 hashing data.
d. It provides functionalities for networking operations.
50. How can you reload a module in Python?
a. By using the reload() function from the module keyword.
b. By importing the module again.
c. By deleting the module file and creating a new one with the same
name.
d. By using the refresh() function from the module keyword.
51. Which module is used for working with MySQL databases in
Python?
a. mysql
b. mysqldb
c. pymysql
d. sqldb
52. What is the purpose of the fractions module in Python?
a. It provides functionalities for creating graphical user interfaces.
b. It provides functionalities for performing mathematical
operations with fractions.
c. It provides functionalities for storing and manipulating large
numbers.
d. It provides functionalities for networking operations.
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
55. What is the purpose of the tkinter 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 interacting with the operating
system.
d. It provides functionalities for networking operations.
56. How can you install a module in Python using Anaconda?
a. Run the command “conda install module_name” in the terminal.
b. Run the command “pip install module_name” in the terminal.
c. Download the module file and copy it to the Anaconda
installation directory.
d. Use the import keyword to import the module directly from the
file.
57. Which module is used for working with PostgreSQL databases in
Python?
a. psycopg2 c. pgsqldb
b. postgre d. pymssql
58. What is the purpose of the pathlib 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 working with file and directory
paths.
d. It provides functionalities for networking operations.
59. How can you install a module in Python from a GitHub
repository?
a. Download the repository as a ZIP file, extract it, and run the
command “pip install extracted_folder_path” in the terminal.
b. Run the command “git clone repository_url” in the terminal,
navigate to the cloned folder, and run the command “pip install .”
in the terminal.
c. Run the command “pip install repository_url” in the terminal.
d. Download the repository as a ZIP file, extract it, and copy the
module file to the Python installation directory.
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.
62. How can you import a module with an alias in Python?
a. By using the keyword as followed by the alias name after the
module name.
b. By using the keyword using followed by the alias name after the
module name.
c. By using the import_alias() function from the module keyword.
d. By importing the module and then assigning the alias using the
equals (=) operator.
63. Which module is used for working with MongoDB databases in
Python without using pymongo?
a. mongo-driver
b. nosql-python
c. mongodb
d. py-mongo
64. How do you import a module named example in Python?
a. import example
b. import module example
c. use example
d. from example import *
65. What is the purpose of the dir() function in Python?
a. Displaying the directory structure
b. Listing all files in the current directory
c. Listing the attributes of an object or module
d. Creating a new directory
66. In Python, what is the role of the __init__.py file in a
directory?
a. It indicates the end of the module
b. It initializes variables in a module
c. It marks the directory as a Python package
d. It is not a valid file in Python
67. How can you access variables defined in a module in Python?
a. By using the from module import * statement
b. By prefixing the variable with the module name
c. By importing the module and using dot notation
d. By using the use module statement
68. What is the purpose of the __name__ attribute in Python?
a. To store the module’s name
b. To check if the module is named
c. To identify whether the module is the main program or imported
d. To access the module’s documentation
69. What is the significance of the if __name__ ==
“__main__”: block in Python modules?
a. It checks if the module is named “main”
b. It is required for all Python modules
c. It contains the main program that should be executed when the
module is run
d. It is used for importing modules
70. Which of the following statements is used to reload a previously
imported module in Python?
a. reload(module)
b. refresh module
c. importlib.reload(module)
d. reload_module(module)
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
72. How can you create an alias for a module in Python?
a. import as
b. module as alias
c. import module alias
d. from module import alias
73. What is the purpose of the __doc__ attribute in Python modules?
a. To store the module’s documentation string
b. To check if the module is documented
c. To access the module’s source code
d. To define the module’s documentation
74. How can you install a Python module using pip?
a. pip install module
b. install module
c. python install module
d. module install
75. What is the purpose of the __file__ attribute in Python
modules?
a. To store the module’s file name
b. To check if the module has a file
c. To access the module’s source code
d. To store the module’s file path
76. How do you create a Python module?
a. By creating a directory with the module name
b. By using the create module command
c. By defining functions and variables in a file with a .py extension
d. By importing an existing 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
78. What is the purpose of the sys.path list in Python?
a. To store the module’s source code
b. To define the module’s path
c. To specify the search path for modules
d. To check if a module is in the system path
79. How can you remove a Python module from memory?
a. unload module
b. remove module
c. delete module
d. importlib.invalidate_caches()
80. What is the purpose of the __all__ attribute in Python modules?
a. To define a list of all available modules
b. To specify which names should be imported when using from
module import *
c. To list all modules installed on the system
d. To store the module’s documentation
81. What does the globals() function in Python return in the
context of modules?
a. The module’s global variables
b. The names of all modules
c. The module’s functions
d. The global variables of the main program
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
83. What is the purpose of the importlib module in Python?
a. To import other modules
b. To reload modules
c. To create new modules
d. To check if a module is installed
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”
85. What is the purpose of the importlib.import_module()
function in Python?
a. To import a module with a specified name
b. To check if a module is imported
c. To install a new module
d. To remove a module from memory
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
87. What is the purpose of the importlib.import_module()
function in Python?
a. To import a module with a specified name
b. To check if a module is imported
c. To install a new module
d. To remove a module from memory
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
89. What is the primary purpose of the __file__ attribute in
Python modules?
a. To store the module’s file name
b. To check if the module has a file
c. To access the module’s source code
d. To store the module’s file path
90. In Python, what is the role of the __init__.py file in a
directory?
a. It indicates the end of the module
b. It initializes variables in a module
c. It marks the directory as a Python package
d. It is not a valid file in Python
91. How can you access variables defined in a module in Python?
a. By using the from module import * statement
b. By prefixing the variable with the module name
c. By importing the module and using dot notation
d. By using the use module statement
92. What is the purpose of the __doc__ attribute in Python
modules?
a. To store the module’s documentation string
b. To check if the module is documented
c. To access the module’s source code
d. To define the module’s documentation
93. What is the significance of the if __name__ ==
“__main__”: block in Python modules?
a. It checks if the module is named “main”
b. It is required for all Python modules
c. It contains the main program that should be executed when the
module is run
d. It is used for importing modules
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
96. Which module is used for working with mathematical functions in
Python?
a. maths c. math
b. calc d. numeric
97. How can you create a custom module in Python?
a. Save a text file with functions and variables
b. Use the create_module() function
c. Import an empty module and add functions
d. Use the make_module() statement
98. What is the purpose of the sys module in Python?
a. It provides system-level operations
b. It is used for creating GUI applications
c. It handles mathematical operations
d. It is a part of the standard library
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
101. How can you uninstall a Python module using pip?
a. uninstall module_name
b. pip remove module_name
c. delete module_name
d. pip uninstall module_name
102. What does the __name__ attribute represent in a Python
module?
a. It is the name of the module file
b. It is the author’s name
c. It is the module’s version
d. It is a special variable that indicates if the module is run as the
main program
103. Which module is used for working with compressed files in
Python?
a. gzip c. zipfile
b. compress d. archive
104. What is the purpose of the platform module in Python?
a. It provides information about the Python interpreter
b. It is used for platform-specific operations
c. It is used to create graphical user interfaces
d. It is a part of the standard library
105. What is the purpose of the __init__ method in a Python
module?
a. It initializes the module’s version
b. It is a constructor method for the module
c. It signifies the end of the module
d. It imports other modules
106. Which function is used to reload a previously imported module in
Python?
a. reload() c. renew()
b. refresh() d. import_again()
107. What is the purpose of the __all__ attribute in a Python
module?
a. It lists all the functions and variables that should be imported
when using from module import *
b. It contains the documentation for the module
c. It specifies the aliases for functions and variables
d. It is not a valid attribute in Python modules
108. In Python, what is the role of the site-packages directory?
a. It stores Python source files
b. It is the default location for user-specific modules
c. It contains built-in modules
d. It is used for temporary file storage
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
111. Which module is used for working with command-line arguments
in Python?
a. cmdline c. sys
b. args d. commandline
112. What does the __file__ attribute represent in a Python
module?
a. It is the file’s creation date
b. It is the author’s name
c. It is the full path of the module’s source file
d. It is the module’s version
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
116. What is the purpose of the pickle module in Python?
a. It is used for working with pickles and preserves
b. It provides support for database operations
c. It serializes and deserializes Python objects
d. It is used for image processing
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
118. Which module is used for working with network-related
operations in Python?
a. net c. socket
b. network d. web
119. What is the purpose of the subprocess module in Python?
a. It provides support for regular expressions
b. It handles subprocesses and system commands
c. It is used for image manipulation
d. It is a part of the standard library
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
121. Which module is used for working with environment variables in
Python?
a. env c. os.environ
b. variables d. config
122. What is the purpose of the configparser module in Python?
a. It is used for configuration management
b. It handles matrix operations
c. It is a part of the standard library
d. It provides support for file I/O
123. How can you create a virtual environment in Python?
a. create venv
b. python -m venv myenv
c. virtualenv create myenv
d. venv -create myenv
124. Which module is used for working with logging in Python?
a. log c. logger
b. logging d. logmanager
125. What is a Python namespace?
a. A reserved keyword in Python
b. A collection of modules
c. A container for variables and functions
d. A file that contains Python code
126. In Python, what is the purpose of a module-level variable?
a. It can only be accessed within a function
b. It is accessible globally within the module
c. It is a variable defined inside a class
d. It is used for exception handling
127. How does Python avoid naming conflicts between modules?
a. By restricting module names to a maximum length
b. By using unique identifiers for each module
c. By encapsulating module code in classes
d. By using namespaces
128. What is the purpose of the from module import * statement?
a. It imports all functions and variables from the module
b. It imports the main function from the module
c. It creates an alias for the module
d. It is not a valid import statement
129. What is a local namespace in Python?
a. A namespace defined within a function
b. The global namespace
c. The namespace of the main program
d. A reserved keyword
130. In Python, what does the globals() function return?
a. The global namespace
b. The local namespace
c. The built-in namespace
d. The module-level namespace
131. Which keyword is used to declare a variable as global in a
function?
a. local
b. global
c. variable
d. gvar
132. What is the purpose of the nonlocal keyword in Python?
a. It declares a variable as nonlocal
b. It specifies a variable as global
c. It is used for exception handling
d. It refers to a variable in the nearest enclosing scope that is not
global
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
135. In Python, what is the purpose of the __name__ attribute?
a. It is the name of the module file
b. It is the name of the function
c. It is a special variable that indicates the module’s name
d. It is the version number of the module
136. What is the significance of the __main__ namespace in Python?
a. It is the main function of the module
b. It is the top-level namespace
c. It is the namespace of the main program
d. It is used for exception handling
137. How can you create a custom namespace in Python?
a. By using the namespace() function
b. By defining a class
c. By using the create_namespace statement
d. By importing the namespace module
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
139. What is the purpose of the __init__.py file in a package?
a. It initializes the package variables
b. It is required for every package
c. It signifies that the directory should be considered a Python
package
d. It contains the documentation for the package
140. In Python, what is a subpackage?
a. A package with a longer name
b. A package that contains only functions
c. A package within another package
d. A package with a higher version number
141. What is the purpose of the __all__ attribute in a module?
a. It lists all the functions and variables that should be imported
when using from module import *
b. It is used to define private variables
c. It is used for exception handling
d. It is not a valid attribute in Python modules
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
143. What is the purpose of the __doc__ attribute in Python?
a. It is a reserved keyword
b. It contains the documentation for the module
c. It is used for exception handling
d. It is the version number of the module
144. Which statement is used for creating a namespace in Python?
a. create namespace
b. namespace = {}
c. new namespace
d. namespace()
145. How do you create a module in Python?
a. By defining a class
b. By creating a new Python file with functions and variables
c. By importing an existing module
d. By using the module() function
146. What is the purpose of the __name__ attribute in a Python
module?
a. It is a reserved keyword
b. It is used to check the module’s version
c. It contains the documentation for the module
d. It helps identify if the module is run as the main program or
imported
147. In a Python module, how can you make a function or variable
private (accessible only within the module)?
a. By using the private keyword
b. By adding a double underscore (__) before the function or
variable name
c. By placing the function or variable in a separate file
d. By using the hidden keyword
148. What is the purpose of the if __name__ == “__main__”:
block in a Python module?
a. It is required for every module.
b. It is a syntax error.
c. It ensures that the module is run as the main program and not
imported.
d. It defines the main function of the module.
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
150. What is the purpose of the __init__.py file in a directory
containing Python modules?
a. It is a syntax error
b. It is used to initialize all variables in the module
c. It signifies that the directory should be considered a Python
package
d. It contains the main function of the package
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
152. What is the purpose of the __all__ attribute in a module?
a. It is used for exception handling
b. It lists all the functions and variables that should be imported
when using from module import *
c. It contains the documentation for the module
d. It defines global variables in the module
153. How can you document a module in Python?
a. By adding comments at the beginning of the module
b. By using the doc keyword
c. By creating a separate documentation file
d. By using triple-quoted strings at the beginning of the module
154. What is the purpose of the __doc__ attribute in Python?
a. It contains the documentation for the module
b. It is a reserved keyword
c. It defines global variables in the module
d. It is used to check the module’s version
155. How do you reload a module in Python?
a. By using the reload() function from the importlib module
b. By restarting the Python interpreter
c. By deleting and recreating the module file
d. By using the refresh() function
156. What is the purpose of the dir() function in Python?
a. It displays the content of the current directory
b. It returns a list of all attributes of an object, including functions
and variables in a module
c. It is used for exception handling
d. It is a reserved keyword
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
158. What is the purpose of the sys.path variable in Python?
a. It is used to store the path of the Python interpreter
b. It is a reserved keyword
c. It contains the paths where Python looks for modules to import
d. It is the location where Python stores temporary files
159. What happens if a module is imported more than once in a
program?
a. Python automatically merges the module code
b. It raises a syntax error
c. The module code is executed only once, and subsequent imports
use the already loaded module
d. It creates separate instances of the module
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
161. What is the purpose of the __file__ attribute in a Python
module?
a. It contains the documentation for the module
b. It is the version number of the module
c. It is used to check the module’s version
d. It is the full path of the module’s source file
162. What is the error in the following code:
import math
result = math.square(4)
a. ImportError: cannot import name ‘square’ from ‘math’
b. AttributeError: module ‘math’ has no attribute ‘square’
c. TypeError: ‘module’ object is not callable
d. No error
163. What is the error in the following code:
from datetime import now
current_time = now()
a. ImportError: cannot import name ‘now’ from ‘datetime’
b. AttributeError: module ‘datetime’ has no attribute ‘now’
c. TypeError: ‘module’ object is not callable
d. No error
164. What is the error in the following code:
import os
current_directory = os.getcwd()
print(current_directory())
a. ImportError: cannot import name ‘getcwd’ from ‘os’
b. AttributeError: ‘str’ object has no attribute ‘getcwd’
c. TypeError: ‘str’ object is not callable
d. No error
165. What is the error in the following code:
from random import choice
items = [1, 2, 3, 4, 5]
selected_item = choice(items)
print(select_item)
a. ImportError: cannot import name ‘choice’ from ‘random’
b. NameError: name ‘select_item’ is not defined
c. AttributeError: ‘module’ object has no attribute ‘select_item’
d. No error
166. What is the error in the following code:
import sys
sys.exit("Exiting the program")
a. ImportError: cannot import name ‘exit’ from ‘sys’
b. AttributeError: module ‘sys’ has no attribute ‘exit’
c. SystemExit: Exiting the program
d. No error
167. What is the error in the following code:
from math import sqrt
result = sqrt(-1)
a. ImportError: cannot import name ‘sqrt’ from ‘math’
b. AttributeError: module ‘math’ has no attribute ‘sqrt’
c. ValueError: math domain error
d. No error
168. What is the error in the following code:
from datetime import datetime
current_time = datetime.now
print(current_time())
a. ImportError: cannot import name ‘datetime’ from ‘datetime’
b. TypeError: ‘builtin_function_or_method’ object is not callable
c. AttributeError: ‘datetime’ object has no attribute ‘now’
d. No error
169. What is the error in the following code:
from os import path
file_exists =
path.exists("/nonexistent/file.txt")
a. ImportError: cannot import name ‘path’ from ‘os’
b. AttributeError: module ‘os’ has no attribute ‘path’
c. FileNotFoundError: [Errno 2] No such file or directory:
‘/nonexistent/file.txt’
d. No error
170. What is the error in the following code:
from random import randint
random_number = randint(1, 10)
print(random_number)
a. ImportError: cannot import name ‘randint’ from ‘random’
b. AttributeError: module ‘random’ has no attribute ‘randint’
c. TypeError: ‘module’ object is not callable
d. No error
171. What is the error in the following code:
from urllib.request import open
response = open("https://www.example.com")
a. ImportError: cannot import name ‘open’ from ‘urllib.request’
b. AttributeError: module ‘urllib.request’ has no attribute ‘open’
c. TypeError: ‘module’ object is not callable
d. No error
172. Which keyword is used to create a Python module?
a. import
b. def
c. class
d. module
173. Can a Python module contain classes?
a. Yes, only one class per module
b. No, modules can only contain functions
c. Yes, multiple classes in a single module are allowed
d. Only if the module is imported using the “class” keyword
174. What is the purpose of the “init.py” file in a module?
a. It is the main module file
b. It initializes the module
c. It is mandatory for the module to be recognized as a package
d. It is responsible for importing other modules
175. Which function is used to reload a module?
a. reload(module_name)
b. import module_name
c. from module_name import reload
d. There is no built-in function to reload a module
176. How do you access a function from an imported module?
a. module_name.function_name()
b. function_name.module_name()
c. module_name->function_name()
d. module_name.function_name
177. Which statement is used to raise an exception manually in Python?
a. return
b. break
c. continue
d. raise
178. How do you create an alias for a module?
a. import module_name as alias_name
b. from module_name import alias_name
c. import alias_name as module_name
d. as alias_name = module_name
179. What is the purpose of "name" variable in a module?
a. It contains the module’s name
b. It is used to create an alias for the module
c. It is set to “main” if the module is run directly
d. It is required to access any function within the module
180. How do you check if a module is installed in Python?
a. use the “python -m <module_name>” command
b. check the existence of a module using the os module
c. use the “import” statement and catch the ImportError
d. use the “name” variable to verify if the module is loaded
181. Which module is used for sending emails in Python?
a. smtplib
b. email
c. imaplib
d. poplib
182. What is the purpose of the “all” variable in a module?
a. It defines the list of all functions and classes in a module
b. It is used to import all modules within a package
c. It specifies the access control for names in a module
d. It is required to access any function within the module
183. How can you create a custom Python module?
a. Save a text file with a .mod extension
b. Save a Python script with a .py extension
c. Save a binary file with a .bin extension
d. Save a JSON file with a .json extension
184. How do you access a function from a module in Python?
a. Declare the function as global in your code
b. Use the module name followed by a dot notation
c. Import the function separately into your code
d. Define the function inside your code
185. Which of the following statements is true about Python modules?
a. Modules cannot be reused across different programs
b. Modules always need to be imported explicitly
c. Modules can only contain classes, not functions
d. Modules can be installed and imported from external sources
186. What is the recommended way to handle errors in Python
modules?
a. Using try-except blocks
b. Using if-else statements
c. Ignoring the errors
d. Using the assert keyword
187. Which Python statement is used to import all functions and
variables from a module directly into the current namespace?
a. from module import *
b. import all from module
c. import module as all
d. import * from module
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
189. Which of the following is a valid module name in Python?
a. my-module c. my module
b. my_module d. myModule
190. What will happen if you try to import a non-existent module in
Python?
a. An error will be raised at runtime
b. Python will automatically create the module
c. The import statement will be ignored
d. A warning will be displayed but the import will succeed
191. How can you access the predefined modules in Python?
a. By importing them using the import keyword
b. By defining them in your own code
c. By downloading them from the internet
d. By creating them from scratch
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
193. Which method is used to import specific functions or variables
from a module in Python?
a. from module import function
b. import function from module
c. import module.function
d. function from module
194. How can you execute a Python module as a standalone script?
a. By running the module file with the Python interpreter
b. By importing the module and calling its main function
c. By executing the module’s __main__ function
d. By specifying the module name in the command line arguments
195. How can you import a module from a different directory in
Python?
a. By specifying the absolute path of the module file
b. By using the importlib module
c. By appending the directory to the system path
d. By renaming the module file to match the directory name
196. What is the purpose of the __pycache__ directory in Python?
a. It contains cached bytecode files for faster import
b. It contains backup files of the module
c. It is used to store temporary files during module execution
d. It is not a valid directory in Python
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
199. What will be the output of the following code:
import mymodule
print(dir(mymodule))
a. The list of all available functions in the module
b. A syntax error, missing modules parentheses
c. The list of all built-in Python modules
d. The list of attributes and methods in the module
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
201. Which module is used to create and manage threads in Python?
a. threading
b. thread
c. concurrent
d. multiprocessing
202. How can you import a specific module within a package in
Python?
a. By using the importlib module’s import_module method
b. By using the package and module names separated by a dot
c. By importing the package as a module and then accessing the
module
d. By specifying the module name in the package’s __init__.py file
203. What will be the output of the following code:
import mymodule
print(mymodule.__name__)
a. The name of the module file
b. The name of the class defined in the module
c. The name of the module’s parent package
d. The name of the module itself
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
205. Which module is used to handle network programming in Python?
a. socket
b. network
c. connect
d. internet
206. What will be the output of the following code:
import mymodule
print(mymodule.__doc__)
a. The empty string, as the module does not have a docstring
b. The name of the module
c. The file path of the module
d. The docstring specified in 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
208. Program code making use of a given module is called a ______ of
the module.
a. Client
b. Docstring
c. Interface
d. Modularity
209. A Python module is a file with the _____ file extension that
contains valid Python code.
a. .pymodule
b. .module
c. .pym
d. .py
210. What will be the output of the following Python code:
from math import factorial
print (math.factorial (5))
a. 120
b. Nothing is printed
c. Error, method factorial does not exist in math module
d. Error, the statement should be: print(factorial(5))
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
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
2 b 52 b 102 d 152 b 202 b
3 b 53 a 103 c 153 d 203 d
4 c 54 a 104 b 154 a 204 a
5 d 55 a 105 b 155 a 205 a
6 b 56 a 106 a 156 b 206 d
7 b 57 a 107 a 157 b 207 a
8 b 58 c 108 b 158 c 208 a
9 c 59 b 109 c 159 c 209 d
10 b 60 a 110 c 160 c 210 d
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
50 b 100 a 150 c 200 b
CHAPTER 13
Packages
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
2. What is the purpose of using packages in Python?
a. To organize and structure code
b. To improve code execution speed
c. To add additional functionality to Python
d. To create graphical user interfaces
3. What is a package in Python?
a. A collection of modules
b. A collection of classes
c. A collection of functions
d. A collection of variables
4. How do you import a package in Python?
a. import packagename
b. from package import packagename
c. include package.packagename
d. import packagename.package
5. What is the purpose of using packages in Python?
a. To organize and distribute modules
b. To define variables
c. To define classes
d. To import functions
6. Which statement is used to import a specific module from a
package?
a. import packagename
b. from packagename import module
c. include packagename.module
d. import packagename.module
7. How can you check the list of modules available in a package?
a. import packagename
b. dir(packagename)
c. list(packagename)
d. pkg_list(packagename)
8. How do you install a package in Python?
a. pip install packagename
b. install packagename
c. include packagename
d. setup packagename
9. Which function is used to uninstall a package in Python?
a. pip uninstall packagename
b. remove packagename
c. delete packagename
d. uninstall packagename
10. How do you upgrade a package to its latest version?
a. pip upgrade packagename
b. upgrade packagename
c. pip install -U packagename
d. pip update packagename
11. What is the purpose of using __init__.py file in a package?
a. To specify the package version
b. To define module-level attributes
c. To initialize package-wide variables
d. To indicate that a directory is a Python package
12. How do you access a specific module from a package?
a. import module from packagename
b. from packagename import module
c. packagename.module
d. packagename.package.module
13. What is the difference between a module and a package in
Python?
a. A module can contain multiple packages
b. A package can contain multiple modules
c. A module can only contain functions
d. A package can only contain classes
14. Which command is used to list all installed packages in Python?
a. pip list c. show packages
b. list packages d. package list
15. How can you import a specific module from a package in Python?
a. import package_name
b. from package_name import module_name
c. import module_name from package_name
d. package_name.module_name
16. Which keyword is used to import an entire package in Python?
a. import c. from
b. import all d. use
17. What is the purpose of the __init__.py file in a Python
package?
a. It indicates that the directory is a package
b. It contains initialization code for the package
c. It holds the package documentation
d. It allows the package to be imported
18. Which of the following is an example of a built-in Python
package?
a. numpy c. math
b. matplotlib d. pandas
19. Which package is commonly used for scientific computing in
Python?
a. numpy c. math
b. matplotlib d. pandas
20. What does the command "pip install package_name" do?
a. Installs a Python package from the PyPI repository
b. Creates a new package with the specified name
c. Uninstalls a previously installed package
d. Updates an existing package to the latest version
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
24. How can you uninstall a Python package using pip?
a. pip uninstall package_name
b. pip remove package_name
c. pip delete package_name
d. pip deactivate package_name
25. Which package is commonly used for data analysis in Python?
a. pandas c. matplotlib
b. numpy d. scipy
26. What does the command "pip freeze" do?
a. Displays a list of installed packages and their versions
b. Freezes the execution of a Python script
c. Removes all installed packages
d. Uninstalls a specific package
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
28. Which package is commonly used for plotting data in Python?
a. numpy c. matplotlib
b. pandas d. scipy
29. What does the command "from package_name import \*"
do?
a. Imports all functions and objects from the package
b. Imports a specific function or object from the package
c. Imports all sub-packages from the package
d. Imports the package itself, but not its sub-packages
30. How can you create your own Python package?
a. Create a new directory and place your modules inside
b. Use the command “pip create package_name”
c. Write the package code directly in your Python script
d. Download a pre-built package from the internet
31. How can you import a module from a sub-package within a
package?
a. import package_name
b. from package_name import module_name
c. import subpackage_name.module_name
d. package_name.subpackage_name.module_name
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
35. Which package is commonly used for interacting with databases in
Python?
a. sqlalchemy c. sqlite3
b. pickle d. requests
36. What does the command "pip show package_name" do?
a. Shows detailed information about the specified package
b. Displays the source code of the specified package
c. Lists all available versions of the specified package
d. Uninstalls the specified package
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
38. What is the purpose of the __name__ attribute in a Python
package?
a. It provides the name of the package
b. It determines the location of the package
c. It keeps track of the package version
d. It identifies the entry point of the package
39. Which package is commonly used for machine learning in Python?
a. sklearn c. pandas
b. tensorflow d. matplotlib
40. What does the command "pip install -r
requirements.txt" do?
a. Installs the packages listed in the requirements.txt file
b. Removes all installed packages
c. Creates a new requirements.txt file
d. Updates the packages listed in the requirements.txt file
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
42. Which package is commonly used for web scraping in Python?
a. beautifulsoup c. requests
b. scrapy d. selenium
43. What does the command "pip install --upgrade pip"
do?
a. Upgrades the pip package to the latest version
b. Upgrades all installed packages to their latest versions
c. Uninstalls the pip package
d. Downgrades the pip package to a specific version
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
45. Which package is commonly used for deep learning in Python?
a. tensorflow c. pytorch
b. keras d. scikit-learn
46. What does the command "pip install -e ." do?
a. Installs the package in editable mode from the current directory
b. Creates a new package with the specified name and installs it
c. Exports the current package to a different location
d. Executes the package’s main script
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
48. What package allows you to interact with relational databases in
Python?
a. sqlite3
b. sqlalchemy
c. pyodbc
d. mysql-connector-python
49. What package allows you to send HTTP requests in Python?
a. requests c. http.client
b. urllib d. httplib2
50. How can you install system-wide packages in Python using pip?
a. sudo pip install package_name
b. pip install package_name -g
c. pip install package_name --global
d. pip install package_name --system
51. Which package allows you to serialize and deserialize Python
objects?
a. json c. xml
b. pickle d. csv
52. What package allows you to handle regular expressions in
Python?
a. re c. pcre
b. regex d. regexp
53. What package allows you to interact with the operating system in
Python?
a. os c. pathlib
b. sys d. subprocess
54. How can you install a package from a specific source distribution
file 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.whl
55. Which package is commonly used for data visualization in
Python?
a. matplotlib
b. seaborn
c. plotly
d. bokeh
56. What does the command "pip install -U package_name"
do?
a. Upgrades the specified package to the latest version
b. Uninstalls the specified package
c. Installs the specified package from the PyPI repository
d. Updates all installed packages to their latest versions
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
63. Which package is commonly used for generating random numbers
in Python?
a. random c. os
b. numpy d. math
64. What does the command "pip install package_name --
index-url https://example.com" do?
a. Installs the package from a specific index URL
b. Changes the default index URL for all future installations
c. Adds the specified index URL to the list of available indexes
d. Removes the specified index URL from the list of available
indexes
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
69. Which package is commonly used for working with images in
Python?
a. PIL c. matplotlib
b. opencv d. skimage
70. What does the command "pip install
package_name>=version_number" do?
a. Installs the specified package with a minimum version number
b. Installs the specified package with a maximum version number
c. Upgrades the specified package to the latest version, if available
d. Uninstalls the specified package with a version number greater
than or equal to the specified version
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
72. What does the command "pip install --pre
package_name" do?
a. Installs the latest pre-release version of the specified package
b. Removes all pre-release versions of the specified package
c. Downloads the package’s pre-release documentation
d. Installs the specified package with additional pre-release features
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
78. What does the command "pip install --ignore-
installed package_name" do?
a. Ignores any previously installed versions of the specified package
b. Forces the installation of all package dependencies
c. Removes the specified package and its dependencies if already
installed
d. Installs the package without checking for previously installed
versions
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
85. Which statement is used to import all functions from a module?
a. from module import *
b. import module
c. include module
d. import module.*
86. What is the purpose of using __name__ == "__main__" in a
Python script?
a. To define a main function
b. To specify the module name
c. To execute the code block only if the script is being run directly
d. To import a specific module
87. How do you create an empty package in Python?
a. Create a directory with the desired package name
b. Use the command “python create package packagename”
c. Click on the “New Package” button in the IDE
d. Use the command “create package packagename”
88. Which command is used to install a specific version of a package
in Python?
a. pip install packagename==version
b. install packagename==version
c. pip version packagename
d. pip add packagename version
89. How do you upgrade all packages to their latest versions?
a. pip upgrade-all
b. upgrade-all packages
c. pip install -U *
d. pip update-all
90. What is the purpose of the __init__.py file inside a package?
a. To define package-level attributes
b. To specify the package version
c. To include external modules
d. To run setup code when the package is imported
91. How do you create a sub package inside an existing package in
Python?
a. Create a new directory inside the package directory
b. Use the command “create subpackage packagename
subpackagename”
c. Click on the “New Subpackage” button in the IDE
d. Use the command “python add subpackage packagename
subpackagename”
92. Which statement is used to import a module from a subpackage?
a. from packagename.subpackagename import module
b. import module from packagename.subpackagename
c. packagename.subpackagename.module
d. import packagename.subpackagename.module
93. How do you remove a package from the Python environment
completely?
a. Remove the package’s directory manually
b. uninstall packagename
c. pip remove packagename
d. Use the command “python delete package packagename”
94. What is the purpose of the __pycache__ directory in a Python
package?
a. To store compiled bytecode files for faster subsequent imports
b. To store package documentation files
c. To store package configuration files
d. To store backup files of the package
95. How do you upgrade a specific package to a specific version using
pip?
a. pip upgrade packagename==version
b. upgrade packagename version
c. pip install packagename==version
d. pip update packagename==version
96. What is the purpose of the __all__ variable in a
module/package?
a. To indicate that all functions/classes should be imported by
default
b. To specify the version of the module/package
c. To limit the list of functions/classes that are imported when using
“import *”
d. To enable/disable debugging mode in the module/package
97. How do you import a module from a package without importing
other modules within the package?
a. import packagename
b. from packagename import module
c. include packagename.module
d. import packagename.module
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”
99. How do you install a package from a local .tar.gz file?
a. pip install package.tar.gz
b. install package.tar.gz
c. pip add package.tar.gz
d. pip extract package.tar.gz
100. What is the purpose of the site-packages directory in the
Python installation?
a. To store the source code for all installed packages
b. To store the documentation for all installed packages
c. To store the compiled bytecode files for all installed packages
d. To store the test cases for all installed packages
101. How do you check the version of a specific package in Python?
a. Use the command “pip show packagename”
b. Use the command “pip version packagename”
c. import packagename and access the __version__ attribute
d. Use the command “version packagename”
102. What is the purpose of the "__pycache__" directory in Python
3?
a. To store temporary files generated during package installation
b. To store compiled bytecode files for faster subsequent imports
c. To store package-related configuration files
d. To store backup files of the package
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
104. What is the purpose of the "requirements.txt" file in a
Python package?
a. To list all the required packages and their versions
b. To list the functions provided by the package
c. To list the available modules in the package
d. To specify the package version
105. How do you create a virtual environment in Python?
a. virtualenv create environmentname
b. python create environment environmentname
c. pip create environment environmentname
d. python -m venv environmentname
106. What is the purpose of a virtual environment in Python?
a. To provide isolation and separate package installations between
projects
b. To automatically update all installed packages to their latest
versions
c. To automatically remove unused packages from the system
d. To hide the source code of the project for security purposes
107. How do you activate a virtual environment in Python?
a. activate environmentname
b. environmentname activate
c. pip activate environmentname
d. source environmentname/bin/activate
108. What is the purpose of the "__init__.py" file inside a
subpackage?
a. To define subpackage-specific attributes
b. To specify the subpackage version
c. To include external modules in the subpackage
d. To run subpackage-specific setup code when the subpackage is
imported
109. How do you upgrade multiple packages to their latest versions
using pip?
a. pip upgrade package1 package2 package3
b. upgrade package1 package2 package3
c. pip install -U package1 package2 package3
d. pip update package1 package2 package3
110. What is the purpose of the "__init__.py" file inside a
module?
a. To define module-specific attributes
b. To specify the module version
c. To include external modules in the module
d. To run module-specific setup code when the module is imported
111. How do you import a module from a package with a relative
import statement?
a. from ..package import module
b. import package.module
c. package.module
d. import .package.module
112. What is the purpose of the "__main__.py" file inside a
package?
a. To define the main function of the package
b. To specify the entry point of the package
c. To include external modules in the package
d. To run setup code when the package is executed as a script
113. How do you create a distribution package for Python?
a. Use the command “python create package package_name”
b. Use the command “python setup.py sdist”
c. Use the command “python build package package_name”
d. Use the command “python distribute package package_name”
114. What is the purpose of the "setup.py" file in a Python
distribution package?
a. To specify the version of the package
b. To include external modules in the package
c. To define package-specific attributes
d. To configure the build process and dependencies of the package
115. How do you install a distribution package in Python?
a. Use the command “python install package package_name”
b. Use the command “python setup.py install”
c. Use the command “python add package package_name”
d. Use the command “python distribute package package_name”
116. What is the purpose of the "MANIFEST.in" file in a Python
distribution package?
a. To specify the package version
b. To include external modules in the package
c. To list additional files or directories to be included in the
distribution
d. To configure the build process and dependencies of the package
117. How do you create a Python wheel package?
a. Use the command “python wheel package package_name”
b. Use the command “python create wheel package_name”
c. Use the command “python setup.py bdist_wheel”
d. Use the command “python build wheel package_name”
118. What is the purpose of a Python wheel package?
a. To provide an archive format for distributing Python libraries
b. To include external packages in the distribution
c. To specify the package version
d. To configure the build process and dependencies of the package
119. How do you install a Python wheel package?
a. Use the command “python install wheel package_name”
b. Use the command “python setup.py install_wheel”
c. Use the command “python add wheel package_name”
d. Use the command “pip install package_name.whl”
120. What is the purpose of the "requirements.txt" file in a
Python project?
a. To list the required packages and their versions
b. To list the functions provided by the project
c. To list the available modules in the project
d. To specify the project version
121. How do you install all packages listed in a requirements.txt
file?
a. Use the command “pip install -r requirements.txt”
b. Use the command “pip install-all requirements.txt”
c. Use the command “pip add requirements.txt”
d. Use the command “pip install requirements.txt”
122. What is the purpose of the "__pycache__" directory in Python
3?
a. To store temporary files generated during project installation
b. To store compiled bytecode files for faster subsequent imports
c. To store project-related configuration files
d. To store backup files of the project
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”
124. What is the purpose of the "__init__.py" file in a Python
project?
a. To define project-level attributes
b. To specify the project version
c. To include external modules in the project
d. To run project setup code when the project is imported
125. How do you create a setup.py file for a Python project?
a. Write a Python script named “setup.py” with the required details
b. Use the command “python create setup.py”
c. Use the command “python build setup.py project_name”
d. Use the command “python setup.py create project_name”
126. What is the purpose of the "entry_points" parameter in the
setup.py file?
a. To specify the project version
b. To include external modules in the project
c. To indicate the entry point(s) for the project
d. To define project-specific attributes
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”
128. How do you include external files in a Python package
distribution?
a. Define the files in the setup.py file using the “data_files”
parameter
b. Copy the files into the package directory before running the
distribution command
c. Specify the files in the MANIFEST.in file
d. Include the files in a separate “extras” package within the
distribution
129. What is the purpose of the "install_requires" parameter in
the setup.py file?
a. To list the Python versions compatible with the project
b. To list the required packages and their versions
c. To specify the build requirements for the project
d. To indicate the entry point(s) for the project
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”
131. What is the primary purpose of the random package in Python?
a. File I/O operations
b. Web scraping
c. Generating random numbers
d. Database operations
132. The os package in Python is used for:
a. Scientific computing
b. Interacting with the operating system
c. Database connectivity
d. Web development
133. Which package is commonly used for web scraping in Python?
a. requests c. csv
b. json d. beautifulsoup4
134. What does the pickle package in Python provide?
a. Data serialization
b. Web development
c. Machine learning
d. Text processing
135. The json package in Python is used for:
a. Data serialization
b. File compression
c. Scientific computing
d. Web development
136. What is the purpose of the math package in Python?
a. File I/O operations
b. Mathematical operations
c. Web development
d. Data visualization
137. Which package is commonly used for working with regular
expressions in Python?
a. re c. string
b. regex d. text
138. The requests package in Python is commonly used for:
a. Database operations
b. Web development
c. Scientific computing
d. Mathematical operations
139. The numpy package in Python is primarily used for:
a. Web development
b. Scientific computing
c. File I/O operations
d. Data visualization
140. What does the csv package in Python provide?
a. Data serialization
b. File compression
c. Web development
d. Reading and writing CSV files
141. The sqlite3 package in Python is used for:
a. Working with SQLite databases
b. Scientific computing
c. Web development
d. File compression
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
144. The matplotlib package in Python is commonly used for
__________.
a. Data serialization
b. File compression
c. Data visualization
d. Web development
145. What is the purpose of the collections package in Python?
a. Mathematical operations
b. Working with collections of items
c. Web development
d. Data visualization
146. The pandas package in Python is commonly used for __________.
a. Scientific computing
b. Data manipulation and analysis
c. Web development
d. Mathematical operations
147. The flask package in Python is commonly used for_____________.
a. Web development
b. Data visualization
c. Scientific computing
d. Database operations
148. Which package is commonly used for unit testing in Python?
a. unittest c. testing
b. test d. pytest
149. The xml package in Python is commonly used for____________.
a. Web development
b. Scientific computing
c. Data serialization
d. File I/O operations
150. What does the scrapy package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Data visualization
151. The argparse package in Python is commonly used for
___________.
a. Web development
b. Data visualization
c. Command-line argument parsing
d. Scientific computing
152. The sqlalchemy package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Database operations
d. Data visualization
153. What is the purpose of the logging package in Python?
a. Web development
b. Data visualization
c. Logging messages during program execution
d. Scientific computing
154. The pillow package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Image processing
d. Data visualization
155. What does the pytest package in Python provide?
a. Scientific computing
b. Web development
c. Unit testing framework
d. Data visualization
156. The asyncio package in Python is commonly used for:
a. Web development
b. Asynchronous programming
c. Scientific computing
d. Data visualization
157. What is the purpose of the itertools package in Python?
a. Web development
b. Scientific computing
c. Mathematical operations
d. Providing iterators for efficient looping
158. The tweepy package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Twitter API access
d. Data visualization
159. What does the pytz package in Python provide?
a. Web development
b. Scientific computing
c. Time zone support
d. Data visualization
160. The django package in Python is commonly used for:
a. Web development
b. Scientific computing
c. Database operations
d. Data visualization
161. The flask-restful package in Python is commonly used for:
a. Web development
b. Scientific computing
c. Database operations
d. Creating RESTful APIs with Flask
162. What is the purpose of the beautifulsoup4 package in
Python?
a. Web development
b. Scientific computing
c. Database operations
d. Web scraping
163. The openpyxl package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Excel file manipulation
d. Data visualization
164. What does the requests-html package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. HTML parsing and rendering with requests
165. The paramiko package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Database operations
d. SSH protocol implementation
166. What is the purpose of the pyinstaller package in Python?
a. Web development
b. Scientific computing
c. Creating standalone executables from Python scripts
d. Data visualization
167. The sqlparse package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Database operations
d. Parsing SQL statements
168. What does the geopy package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Geocoding and distance calculation
169. The seaborn package in Python is commonly used for:
a. Scientific computing
b. Web development
c. Data visualization
d. Database operations
170. What is the purpose of the pyyaml package in Python?
a. Scientific computing
b. Web development
c. Data serialization in YAML format
d. Database operations
171. The pyautogui package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Automation of GUI interactions
d. Data visualization
172. What does the pygame package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Game development
173. The cryptography package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Cryptographic operations
174. What is the purpose of the graph-tool package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Graph analysis and manipulation
175. The pyserial package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Serial communication with devices
176. What does the pywhatkit package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Automation of WhatsApp messages
177. The youtube_dl package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Downloading videos from YouTube
178. What is the purpose of the tqdm package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Adding progress bars to loops
179. The zipfile package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Working with zip archives
180. What does the networkx package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Graph analysis and manipulation
181. The pytest fixture tmpdir is commonly used for ___________.
a. File I/O operations
b. Web development
c. Creating temporary directories for testing
d. Scientific computing
182. The pytz package in Python is commonly used for ___________.
a. Web development
b. Scientific computing
c. Time zone support
d. Data visualization
183. What does the cx_Oracle package in Python provide?
a. Scientific computing
b. Web development
c. Database operations with Oracle databases
d. Data visualization
184. The tkinter package in Python is commonly used for
___________.
a. Web development
b. Scientific computing
c. Database operations
d. GUI programming
185. What is the purpose of the pydantic package in Python?
a. Scientific computing
b. Web development
c. Data validation and settings management
d. Database operations
186. The folium package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating interactive maps with Leaflet.js
187. What does the opencv-python package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Computer vision and image processing
188. The pytorch package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Deep learning
189. What is the purpose of the pydub package in Python?
a. Scientific computing
b. Web development
c. Audio processing and manipulation
d. Database operations
190. The asyncpg package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Asynchronous access to PostgreSQL databases
d. Database operations
191. What does the dash package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Building analytical web applications
192. The pyinstaller package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Creating standalone executables from Python scripts
d. Data visualization
193. What is the purpose of the wikipedia-api package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Accessing and parsing Wikipedia content
194. The asyncio package in Python is commonly used for
___________.
a. Web development
b. Asynchronous programming
c. Scientific computing
d. Data visualization
195. What does the pytest-cov plugin provide in the context of
testing with pytest?
a. Scientific computing
b. Web development
c. Code coverage reporting
d. Database operations
196. The pyqt package in Python is commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating desktop applications with Qt
197. The pymongo package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations with MongoDB
d. Data visualization
198. What is the purpose of the dash-bootstrap-components
package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Bootstrap-themed components for Dash applications
199. The pytest-django plugin in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Testing Django applications with pytest
200. What does the docutils package in Python provide?
a. Scientific computing
b. Web development
c. Documentation utilities
d. Database operations
201. The pyarrow package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Efficient Arrow format serialization
202. The tesseract package in Python is commonly used for
_______.
a. Scientific computing
b. Web development
c. Optical character recognition (OCR)
d. Database operations
203. What is the purpose of the h5py package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Working with HDF5 file format
204. The python-docx package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating and updating Word documents
205. What does the pyTelegramBotAPI package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Building bots for the Telegram API
206. The google-api-python-client package in Python is
commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Interacting with Google APIs
207. What is the purpose of the python-Levenshtein package in
Python?
a. Scientific computing
b. Web development
c. Database operations
d. Calculating Levenshtein distances
208. The tika package in Python is commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Extracting text and metadata from various file formats
209. What does the pytzdata package in Python provide?
a. Scientific computing
b. Web development
c. Time zone data for pytz
d. Database operations
210. The scipy package in Python is commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Data visualization
211. What is the purpose of the gunicorn package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. A WSGI HTTP server for running Python web applications
212. The scrapy middleware HttpProxyMiddleware is commonly
used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Rotating HTTP proxies in web scraping
213. What does the googletrans package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Google Translate API wrapper
214. The pycrypto package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Cryptographic operations
215. What is the purpose of the pyTelegramBotAPI package in
Python?
a. Scientific computing
b. Web development
c. Database operations
d. Building bots for the Telegram API
216. The pybind11 package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating Python bindings for C++ code
217. What does the qrcode package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Generating QR codes
218. The pytest-mock plugin in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Mocking objects for testing with pytest
219. What is the purpose of the google-cloud-storage package in
Python?
a. Scientific computing
b. Web development
c. Database operations
d. Interacting with Google Cloud Storage
220. The pyodbc package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations with ODBC databases
d. Data visualization
221. The reportlab package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating PDF documents
222. What does the python-dotenv package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Loading environment variables from a file
223. The psycopg2 package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations with PostgreSQL databases
d. Data visualization
224. What is the purpose of the shutil package in Python?
a. Scientific computing
b. Web development
c. File and directory operations
d. Database operations
225. The dash-html-components package in Python is commonly
used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating HTML components for Dash applications
226. The openai package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Interacting with the OpenAI API
227. What does the marshmallow package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Object serialization and deserialization
228. The pypdf2 package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Reading and manipulating PDF files
229. The pyjwt package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. JSON Web Token (JWT) encoding and decoding
230. What does the geopandas package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Working with geospatial data using pandas
231. The websockets package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Asynchronous WebSocket communication
232. The pathlib module in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. File and path manipulation
d. Database operations
233. What does the datetime module in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Date and time manipulation
234. The pygsheets package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Interacting with Google Sheets API
235. What is the purpose of the dash-cytoscape package in
Python?
a. Scientific computing
b. Web development
c. Database operations
d. Creating interactive network visualizations with Dash
236. The python-binance package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Interacting with the Binance API
237. What does the ipaddress module in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Working with IP addresses and networks
238. The pyinstaller option --onefile is used for
___________.
a. Scientific computing
b. Web development
c. Creating a single executable file from a Python script
d. Database operations
239. What is the purpose of the requests-oauthlib package in
Python?
a. Scientific computing
b. Web development
c. Database operations
d. OAuth support for the requests package
240. The bokeh package in Python is commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Creating interactive and real-time data visualizations
241. What does the tabulate package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Formatting and printing tabular data
242. The google-cloud-bigquery package in Python is
commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations with Google BigQuery
d. Data visualization
243. What is the purpose of the python-box package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Dicts with attribute-style access, a la JavaScript
244. The pyod package in Python is commonly used for ___________.
a. Scientific computing
b. Web development
c. Database operations
d. Outlier detection in multivariate data
245. What does the hypothesis package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. Property-based testing
246. The folium.plugins module in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Adding plugins and enhancements to Folium maps
247. What is the purpose of the simplejson package in Python?
a. Scientific computing
b. Web development
c. Database operations
d. Fast JSON encoding and decoding
248. The opencv-contrib-python package in Python provides:
a. Scientific computing
b. Web development
c. Database operations
d. Additional modules and features for OpenCV
249. The pygments package in Python is commonly used for
___________.
a. Scientific computing
b. Web development
c. Database operations
d. Syntax highlighting for code
250. What does the fastapi package in Python provide?
a. Scientific computing
b. Web development
c. Database operations
d. A fast web framework for building APIs with Python 3.7+
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 a 51 b 101 a 151 c 201 d
2 a 52 a 102 b 152 c 202 c
3 a 53 a 103 b 153 c 203 d
4 a 54 a 104 a 154 c 204 d
5 a 55 a 105 d 155 c 205 d
6 d 56 a 106 a 156 b 206 d
7 b 57 a 107 d 157 d 207 d
8 a 58 a 108 d 158 c 208 d
9 a 59 a 109 c 159 c 209 c
10 c 60 a 110 d 160 a 210 a
11 d 61 a 111 a 161 d 211 d
12 b 62 d 112 b 162 d 212 d
13 b 63 a 113 b 163 c 213 d
14 a 64 a 114 d 164 d 214 d
15 b 65 a 115 b 165 d 215 d
16 a 66 a 116 c 166 c 216 d
17 a 67 a 117 c 167 d 217 d
18 c 68 b 118 a 168 d 218 d
19 a 69 a 119 d 169 c 219 d
20 a 70 a 120 a 170 c 220 c
21 d 71 a 121 a 171 c 221 d
22 c 72 a 122 b 172 d 222 d
23 a 73 a 123 a 173 d 223 c
24 a 74 b 124 d 174 d 224 c
25 a 75 a 125 a 175 d 225 d
26 a 76 a 126 c 176 d 226 d
27 a 77 a 127 a 177 d 227 d
28 c 78 a 128 c 178 d 228 d
29 a 79 a 129 b 179 d 229 d
30 a 80 d 130 a 180 d 230 d
31 d 81 a 131 c 181 c 231 d
32 a 82 c 132 b 182 c 232 c
33 a 83 a 133 d 183 c 233 d
34 d 84 d 134 a 184 d 234 d
35 a 85 a 135 a 185 c 235 d
36 a 86 c 136 b 186 d 236 d
37 a 87 a 137 a 187 d 237 d
38 a 88 a 138 b 188 d 238 c
39 a 89 c 139 b 189 c 239 d
40 a 90 d 140 d 190 c 240 d
41 a 91 a 141 a 191 d 241 d
42 a 92 a 142 b 192 c 242 c
43 a 93 a 143 c 193 d 243 d
44 a 94 a 144 c 194 b 244 d
45 a 95 c 145 b 195 c 245 d
46 a 96 c 146 b 196 d 246 d
47 a 97 b 147 a 197 c 247 d
48 b 98 a 148 a 198 d 248 d
49 a 99 a 149 c 199 d 249 d
50 a 100 c 150 b 200 c 250 d
CHAPTER 14
Object-oriented Programming
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.
Multiple choice questions
1. What is object-oriented programming (OOP)?
a. A programming paradigm that organizes code into objects.
b. An approach to programming that focuses on data structures.
c. A method for developing programs using only functions.
d. A way to optimize code for speed and efficiency.
2. Which of the following is not a principle of object-oriented
programming?
a. Encapsulation c. Polymorphism
b. Inheritance d. Normalization
3. What is a class in Python?
a. A collection of functions
b. A data type
c. An instance of an object
d. A blueprint for creating objects
4. Which keyword is used to define a class in Python?
a. class c. def
b. object d. instance
5. When creating a class, what method is executed automatically
when an object is created?
a. __init__ c. __class__
b. __main__ d. __new__
6. What is the purpose of the __init__ method in a class?
a. To create a new object
b. To initialize the object’s attributes
c. To define the object’s methods
d. To destroy the object
7. Which of the following statements is true about inheritance in
Python:
a. A class can inherit multiple classes.
b. A class can inherit a class and an interface.
c. A class can inherit another class but not an interface.
d. Python does not support inheritance.
8. Which keyword is used to inherit a class in Python:
a. inherit c. inherit_from
b. extends d. None of the above
9. What is method overriding in Python?
a. Reusing a method with different functionality in the derived
class.
b. Renaming a method in the derived class.
c. Adding a new method in the derived class.
Deleting a method in the derived class.
10. Which of the following is an example of encapsulation in Python?
a. Grouping related data and functions into a class.
b. Inheriting attributes from a base class.
c. Overriding a method in a derived class.
d. Accessing a private attribute directly.
11. What is the purpose of the self-parameter in Python class
methods?
a. It refers to the class itself.
b. It refers to the parent class.
c. It refers to the instance of the object.
d. It refers to the derived class.
12. Which access modifier in Python allows attributes/methods to be
accessed from anywhere?
a. private c. public
b. protected d. global
13. Which access modifier in Python allows attributes/methods to be
accessed within the same class and its subclasses?
a. private c. public
b. protected d. global
14. What is method overloading in Python?
a. Having multiple methods with the same name but different
parameters in a class.
b. Having multiple methods with the same name and same
parameters in a class.
c. Having multiple methods with different names but the same
parameters in a class.
d. Having multiple methods with the same name and different return
types in a class.
15. What is the main advantage of using object-oriented
programming?
a. Reusability of code
b. Faster execution speed
c. Smaller program size
d. Simplicity of code
16. In OOP, what is the term used to describe creating an instance of a
class?
a. Instantiating c. Constructing
b. Initializing d. Engendering
17. Which of the following is an example of polymorphism in Python?
a. A function that can accept different types of arguments.
b. A class that can inherit from multiple classes.
c. A method that is defined in the base class and overridden in the
derived class.
d. An attribute that can be accessed from anywhere in the code.
18. What is the purpose of the super() function in Python?
a. To call the __init__ method of the parent class.
b. To terminate the execution of an object.
c. To define a static method in a class.
d. To access the attributes of the derived class.
19. Which of the following is an example of a well-written class in
Python?
a. A class with too many global variables and long method names.
b. A class that does not have any attributes or methods.
c. A class with properly encapsulated attributes and methods.
d. A class with duplicate attributes and inconsistent naming
conventions.
20. What is composition in OOP?
a. Creating objects within objects.
b. Creating objects from a blueprint.
c. Creating objects with predefined attributes.
d. Creating objects with inheritance.
21. What is operator overloading in Python?
a. Changing the behavior of an operator for a user-defined class.
b. Overriding all the operators in a class.
c. Using additional operators that are not built-in to Python.
d. Creating custom operators for specific tasks.
22. Which keyword is used to access the attributes and methods of a
class within itself?
a. self c. this
b. super d. access
23. What is the purpose of the __str__ method in Python?
a. To convert an object to a string representation.
b. To convert a string to an object representation.
c. To convert a class to a string object.
d. To compare two objects for equality.
24. What is multiple inheritance in Python?
a. When a class inherits attributes and methods from multiple
classes.
b. When a class inherits attributes from multiple classes.
c. When a class inherits methods from multiple classes.
d. When a class can inherit a class and an interface.
25. What is the purpose of the del keyword in Python?
a. To delete a class from memory.
b. To delete an object attribute.
c. To delete a method from a class.
d. To delete an entire class hierarchy.
26. How are exceptions handled in object-oriented programming?
a. By using try-except blocks in methods.
b. By using if-else statements in classes.
c. By using loops to handle exception conditions.
d. Exceptions are automatically handled by the compiler.
27. Which of the following is an example of a built-in exception in
Python?
a. InterfaceError
b. TypeError
c. UndefinedFunctionError
d. ProgramError
28. What is the purpose of the @staticmethod decorator in Python?
a. To indicate a static method in a class.
b. To indicate an abstract method in a class.
c. To indicate a class method in a class.
d. To indicate an instance method in a class.
29. What is an abstract class in Python?
a. A class that cannot be instantiated and is meant to be subclassed.
b. A class with only abstract methods.
c. A class that is defined within another class.
d. A class that can inherit from multiple classes.
30. What is the purpose of the isinstance() function in Python?
a. To check if an object is an instance of a specific class.
b. To compare two objects for equality.
c. To convert a string to an integer.
d. To access the attributes of a class.
31. What is the purpose of the __repr__ method in Python?
a. To convert an object to a string representation.
b. To convert a string to an object representation.
c. To compare two objects for equality.
d. To create a more detailed string representation of an object.
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.
33. What is the purpose of the @classmethod decorator in Python?
a. To indicate a class method in a class.
b. To indicate an abstract method in a class.
c. To indicate an instance method in a class.
d. To indicate a static method in a class.
34. What is dynamic binding in Python?
a. The process of linking method calls to their implementations at
runtime.
b. The process of linking variables to their values at compile time.
c. The process of linking classes to their base classes at runtime.
d. The process of linking modules to their imports at compile time.
35. How can you access a private attribute of a class in Python?
a. By using the dot operator directly on the attribute.
b. By using the name mangling convention.
c. By using the @private decorator.
d. By using the @access modifier.
36. What is the purpose of the @property decorator in Python?
a. To define a private attribute in a class.
b. To define a class attribute.
c. To define a static method in a class.
d. To define a getter method for a class attribute.
37. What is the purpose of the @abstractmethod decorator in
Python?
a. To define a private attribute in a class.
b. To define a class attribute.
c. To define an abstract method in a class.
d. To define a static method in a class.
38. What is duck typing in Python?
a. The practice of using ducks as objects in a program.
b. The practice of dynamically typing variables.
c. The practice of using object-oriented programming.
d. The practice of focusing on an object’s behavior rather than its
type.
39. What is method resolution order (MRO) in Python?
a. The order in which methods are executed in a class.
b. The order in which methods are defined in a class.
c. The order in which classes are inherited in multiple inheritance.
d. The order in which classes are defined in a program.
40. How do you create an object of a class in Python?
a. By calling the class name as a function.
b. By using the new() method.
c. By calling the __new__ method.
d. By using the allocate() method.
41. 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 an instance method in a class.
d. To define a static method in a class.
42. What is the difference between a class variable and an instance
variable in Python?
a. A class variable is shared among all instances of a class, while an
instance variable is unique to each instance.
b. A class variable is unique to each instance, while an instance
variable is shared among all instances of a class.
c. A class variable is defined inside a class, while an instance
variable is defined outside a class.
d. A class variable is accessed using the dot operator, while an
instance variable is accessed using the self-keyword.
43. How do you change the value of a class variable in Python?
a. By using the self keyword.
b. By using the @classmethod decorator.
c. By using the dot operator directly on the class name.
d. By using the @staticmethod decorator.
44. What is a constructor in object-oriented programming?
a. A method that is used to create objects.
b. A method that is used to initialize objects.
c. A method that is used to destroy objects.
d. A method that is used to access attributes of an object.
45. How do you define a default argument for a method in Python?
a. By using the self-keyword
b. By specifying the default value in the method definition
c. By using the @staticmethod decorator
d. By using the *args parameter
46. What is the purpose of the @staticmethod decorator in
Python?
a. To define a static method in a class
b. To define an abstract method in a class
c. To define an instance method in a class
d. To define a class method in a class
47. What is the purpose of the __name__ attribute in Python?
a. To access the name of a module.
b. To access the name of a class.
c. To access the name of a method.
d. To access the name of an object.
48. Which method is called when an object is converted to a string
using the str() function?
a. __str__ c. __main__
b. __init__ d. __class__
49. What is a decorator in Python?
a. A function that adds functionality to another function or class.
b. A method that is used to validate input data.
c. A class that is used to override built-in methods.
d. A keyword that is used to define a class.
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.
52. What is the purpose of the self-parameter in Python class
methods?
a. It refers to the class itself.
b. It refers to the parent class.
c. It refers to the instance of the object.
d. It refers to the derived class.
53. What is operator overloading in Python?
a. Changing the behavior of an operator for a user-defined class.
b. Overriding all the operators in a class.
c. Using additional operators that are not built-in to Python.
d. Creating custom operators for specific tasks.
54. What is the purpose of the __repr__ method in Python?
a. To convert an object to a string representation.
b. To convert a string to an object representation.
c. To compare two objects for equality.
d. To create a more detailed string representation of an object.
55. Which keyword is used to access the attributes and methods of a
class within itself?
a. self
b. super
c. this
d. access
56. What is method resolution order in Python?
a. The order in which methods are executed in a class.
b. The order in which methods are defined in a class.
c. The order in which classes are inherited in multiple inheritance.
d. The order in which classes are defined in a program.
57. What is duck typing in Python?
a. The practice of using ducks as objects in a program.
b. The practice of dynamically typing variables.
c. The practice of using object-oriented programming.
d. The practice of focusing on an object’s behavior rather than its
type.
58. What is composition in OOP?
a. Creating objects within objects.
b. Creating objects from a blueprint.
c. Creating objects with predefined attributes.
d. Creating objects with inheritance.
59. What is an abstract class in Python?
a. A class that cannot be instantiated and is meant to be subclassed.
b. A class with only abstract methods.
c. A class that is defined within another class.
d. A class that can inherit from multiple classes.
60. What will be the output of the following Python code:
class test:
def __init__(self,a="Python"):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
a. The program has an error
b. “Python” is displayed
c. Nothing is displayed
d. None of above
61. Which of the following approach is followed by Object Oriented
language during the execution of a program?
a. Top down approach
b. Bottom up approach
c. Top down and bottom up approach
d. None of these
62. How do you define a default argument for a method in Python?
a. By using the self keyword.
b. By specifying the default value in the method definition.
c. By using the @staticmethod decorator.
d. By using the *args parameter.
63. What is the primary purpose of encapsulation in Python OOP?
a. To achieve code modularity
b. To restrict access to class attributes
c. To facilitate code reuse
d. All of the above
64. In Python, what keyword is used to create a new instance of a
class?
a. instance
b. new
c. create
d. None of the above
65. What is the purpose of the super() function in Python OOP?
a. To call a method from the superclass
b. To create a new instance of a class
c. To access private attributes
d. None of the above
66. Which of the following statements about inheritance in Python is
true?
a. A class can inherit from multiple classes
b. Python supports only single inheritance
c. Inheritance is not supported by Python
d. None of the above
67. What is the purpose of the __init__ method in a Python class?
a. To initialize class attributes
b. To create a new instance of the class
c. To define the class methods
d. None of the above
68. What is the significance of the self-parameter in Python class
methods?
a. It represents the class itself
b. It refers to the instance of the class
c. It is used to create a new instance of the class
d. None of the above
69. Which access modifier is used for a private class attribute in
Python?
a. private
b. secret
c. hidden
d. None of the above
70. What is polymorphism in Python OOP?
a. The ability to inherit from multiple classes
b. The ability of a class to take on multiple forms
c. The ability to hide the implementation details
d. None of the above
71. Which built-in function is used to check if an object is an instance
of a particular class?
a. object_instance()
b. isinstance()
c. typeof()
d. None of the above
72. How is method overriding achieved in Python OOP?
a. By using the @override decorator
b. By redefining the method in the subclass
c. By using the super() function
d. None of the above
73. In Python, what is the purpose of the __str__ method in a class?
a. To convert an object to a string representation
b. To define the string data type
c. To create a new instance of the class
d. None of the above
74. What is the role of the @classmethod decorator in Python?
a. It defines a class method
b. It creates an instance of a class
c. It marks a method as private
d. None of the above
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
76. How is a static method defined in a Python class?
a. By using the @staticmethod decorator
b. By using the static keyword
c. By not using any decorator or keyword
d. None of the above
77. What is an abstract class in Python?
a. A class that cannot be instantiated
b. A class with only abstract methods
c. A class without any methods
d. None of the above
78. Which keyword is used to create a child class in Python?
a. child
b. subclass
c. extends
d. None of the above
79. What is the purpose of the __init__ method in Python?
a. To initialize the class
b. To create a new instance of the class
c. To define the class methods
d. None of the above
80. What is the significance of the __doc__ attribute in a Python
class?
a. It contains the documentation string for the class
b. It refers to the class itself
c. It is used to define class methods
d. None of the above
81. How does Python support multiple inheritance?
a. By using the extends keyword
b. By allowing a class to inherit from more than one class
c. By using the implements keyword
d. None of the above
82. What is a mixin in Python OOP?
a. A type of polymorphism
b. A special method in a class
c. A class designed to provide methods to other classes
d. None of the above
83. What is the purpose of the @property decorator in Python?
a. It defines a property in a class
b. It marks a method as private
c. It converts a method into a static method
d. None of the above
84. How is method overloading achieved in Python?
a. By defining multiple methods with the same name but different
parameters
b. By using the @overload decorator
c. By redefining the method in the subclass
d. None of the above
85. What is the purpose of the __del__ method in a Python class?
a. To delete a class instance
b. To define the class destructor
c. To create a new instance of the class
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
87. How does Python handle encapsulation?
a. By using access modifiers like public, private, and protected
b. By relying on naming conventions (single underscore for
protected, double underscore for private)
c. By using decorators such as @property
d. All of the above
88. Which keyword is used to access the attributes of a class in
Python?
a. access c. self
b. get d. None of the above
89. What is the purpose of the issubclass() function in Python?
a. To check if an object is an instance of a class
b. To check if a class is a subclass of another class
c. To check if a method is a subclass of another method
d. None of the above
90. Which of the following statements is true about class attributes in
Python?
a. They are defined inside methods
b. They are shared among all instances of a class
c. They are created using the self-keyword
d. None of the above
91. What is the purpose of the __slots__ attribute in a Python
class?
a. To define class methods
b. To limit the attributes that can be added to an instance
c. To create a new instance of the class
d. None of the above
92. Which built-in function is used to check if an attribute exists in an
object in Python?
a. hasattribute()
b. checkattribute()
c. getattr()
d. None of the above
93. What is the primary purpose of a constructor in Python?
a. To create an instance of a class
b. To initialize class attributes
c. To define class methods
d. None of the above
94. What is the default name of the constructor method in a Python
class?
a. init
b. constructor
c. __init__
d. None of the above
95. How is the constructor invoked in Python when creating a new
instance of a class?
a. Automatically when the class is defined
b. By calling the construct() method
c. Automatically when the __new__ method is defined
d. Automatically when the __init__ method is defined
96. Which keyword is used to refer to the current instance of a class
within the constructor?
a. self
b. this
c. instance
d. None of the above
97. What happens if you define both __init__ and __new__
methods in a Python class?
a. It causes a syntax error
b. The __new__ method takes precedence over the __init__ method
c. The __init__ method takes precedence over the __new__ method
d. Both methods are executed in order
98. Can a class have multiple constructors in Python?
a. Yes, using the __init__ method with different parameters
b. Yes, using the __new__ method with different parameters
c. No, a class can only have one constructor
d. None of the above
99. What is the purpose of the __call__ method in Python?
a. To create a new instance of a class
b. To define a callable object
c. To initialize class attributes
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
101. What is the purpose of a destructor in Python?
a. To delete an instance of a class
b. To initialize class attributes
c. To define the class methods
d. None of the above
102. Which method is automatically called when an object is about to
be destroyed in Python?
a. __delete__
b. __destroy__
c. __del__
d. None of the above
103. What is the purpose of the __new__ method in Python?
a. To create a new instance of a class
b. To initialize class attributes
c. To define the class methods
d. None of the above
104. Can you have a class without a constructor in Python?
a. Yes, a constructor is optional
b. No, every class must have a constructor
c. Only if the class has no attributes
d. None of the above
105. In Python, what is the purpose of the __init_subclass__
method?
a. To initialize subclasses
b. To define a subclass constructor
c. To customize the creation of subclasses
d. None of the above
106. How do you prevent the instantiation of a class in Python?
a. By making the class abstract
b. By using the @abstract decorator
c. By raising an exception in the constructor
d. None of the above
107. What is the purpose of the __str__ method in a Python class?
a. To initialize the class
b. To create a new instance of the class
c. To convert an object to a string representation
d. None of the above
108. Which keyword is used to create an instance of a class in Python?
a. create c. new
b. instance d. None of the above
109. How can you make a parameter mandatory in a Python
constructor?
a. By specifying a default value for the parameter
b. By using the mandatory keyword
c. By not providing a default value for the parameter
d. None of the above
110. What happens if you do not define a constructor in a Python class?
a. It causes a syntax error
b. Python automatically provides a default constructor
c. The class cannot be instantiated
d. None of the above
111. How do you call the constructor of the superclass in Python?
a. By using the super() function
b. By using the base() function
c. By calling the constructor directly
d. None of the above
112. What is the primary purpose of the __call__ method in Python?
a. To create a new instance of a class
b. To define a callable object
c. To initialize class attributes
d. None of the above
113. What is inheritance in Python OOP?
a. The ability to create multiple instances of a class
b. The ability of a class to inherit attributes and methods from
another class
c. The process of creating a new class
d. None of the above
114. What is the primary advantage of using inheritance in Python?
a. It allows a class to create multiple instances
b. It promotes code reusability and modularity
c. It defines new attributes for a class
d. None of the above
115. In Python, what is the keyword used to indicate inheritance?
a. inherit
b. extends
c. inherits
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
117. Which method is automatically called when an object of a subclass
is created in Python?
a. __init__
b. __new__
c. __create__
d. None of the above
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
119. What is method overriding in Python?
a. Redefining a method in the subclass with the same name as in the
base class
b. Creating a new method in the subclass with a different name
c. Hiding a method in the base class
d. None of the above
120. How does Python support multiple inheritance?
a. By using the implements keyword
b. By allowing a class to inherit from more than one class
c. By using the extends keyword
d. None of the above
121. What is the purpose of the super() function in Python
inheritance?
a. To create a new instance of a class
b. To call a method from the superclass
c. To define a method in the subclass
d. None of the above
122. In Python, what is the order of method resolution in multiple
inheritance called?
a. Method Resolution Order
b. Inheritance Order
c. Call Order
d. None of the above
123. What is the significance of the isinstance() function in
Python?
a. To check if an object is an instance of a class
b. To check if a class is a subclass of another class
c. To check if a method is overridden
d. None of the above
124. In Python, what is a diamond problem in the context of multiple
inheritance?
a. A naming conflict between two methods in different classes
b. A conflict arising when a class inherits from two classes with a
common ancestor
c. A problem with the diamond() method
d. None of the above
125. What is the purpose of the @abstractmethod decorator in Python?
a. To define a method as private
b. To mark a method as abstract in an abstract class
c. To create a new instance of a class
d. None of the above
126. In Python, what is an abstract class?
a. A class with only concrete methods
b. A class that cannot be instantiated
c. A class with a single abstract method
d. None of the above
127. What is the purpose of the @staticmethod decorator in
Python?
a. To define a method as private
b. To mark a method as static
c. To create a new instance of a class
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
130. What is the purpose of the __bases__ attribute in a Python
class?
a. To get the base classes of a class
b. To access the base class methods
c. To check if a class is abstract
d. None of the above
131. How can you achieve encapsulation in a Python class?
a. By using access modifiers like public, private, and protected
b. By relying on naming conventions (single underscore for
protected, double underscore for private)
c. By using the @encapsulate decorator
d. All of the above
132. What is the purpose of the issubclass() function in Python?
a. To check if an object is an instance of a class
b. To check if a class is a subclass of another class
c. To check if a method is a subclass of another method
d. None of the above
133. What is the error in the following code:
class MyClass:
def __init__(self, x, y):
self.x = x
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’
134. What is the error in the following code:
class Circle:
def __init__(self, radius):
self.radius = radius
c = Circle()
a. AttributeError: ‘Circle’ object has no attribute ‘radius’
b. TypeError: init() missing 1 required positional argument
c. No error
d. NameError: name ‘Circle’ is not defined
135. What is the error in the following code:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
r = Rectangle(5)
a. TypeError: init() missing 1 required positional argument
b. AttributeError: ‘Rectangle’ object has no attribute ‘width’
c. No error
d. ValueError: too many values to unpack
136. What is the error in the following code:
class Book:
def __init__(self, title):
self.title = title
b = Book()
a. AttributeError: ‘Book’ object has no attribute ‘title’
b. TypeError: init() missing 1 required positional argument
c. No error
d. NameError: name ‘Book’ is not defined
137. What is the error in the following code:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
c = Car("Toyota")
a. TypeError: init() missing 1 required positional argument
b. AttributeError: ‘Car’ object has no attribute ‘model’
c. No error
d. ValueError: too many values to unpack
138. What is the error in the following code:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s = Student(name="Alice", gender="Female")
a. TypeError: init() got an unexpected keyword argument ‘gender’
b. AttributeError: ‘Student’ object has no attribute ‘gender’
c. No error
d. ValueError: too many values to unpack
139. What is the error in the following code:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
e = Employee("John", role="Manager")
a. TypeError: init() got an unexpected keyword argument ‘role’
b. AttributeError: ‘Employee’ object has no attribute ‘role’
c. No error
d. ValueError: too many values to unpack
140. What is the error in the following code:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
d = Dog(name="Buddy", age=3, color="Brown")
a. TypeError: init() got an unexpected keyword argument ‘color’
b. AttributeError: ‘Dog’ object has no attribute ‘color’
c. No error
d. ValueError: too many values to unpack
141. What is the error in the following code:
class Computer:
def __init__(self, brand):
self.brand = brand
c = Computer(brand="Dell", model="Inspiron")
a. TypeError: init() got an unexpected keyword argument ‘model’
b. AttributeError: ‘Computer’ object has no attribute ‘model’
c. No error
d. ValueError: too many values to unpack
142. What is the error in the following code:
class Shape:
def __init__(self, name):
self.name = name
s = Shape("Square")
print(s.area)
a. AttributeError: ‘Shape’ object has no attribute ‘area’
b. TypeError: ‘Shape’ object is not callable
c. No error
d. ValueError: name ‘area’ is not defined
143. What is the error in the following code:
class Animal:
def speak(self):
pass
a = Animal()
a.speak()
a. SyntaxError: pass statement not allowed
b. TypeError: Can’t instantiate abstract class Animal with abstract
methods speak
c. No error
d. ValueError: ‘Animal’ object has no attribute ‘speak’
144. What is the error in the following code:
class Bird:
def fly(self):
print("Flying")
b = Bird()
b.walk()
a. AttributeError: ‘Bird’ object has no attribute ‘walk’
b. TypeError: ‘Bird’ object is not callable
c. No error
d. ValueError: name ‘walk’ is not defined
145. What is the error in the following code:
class Person:
def __init__(self, name):
self.name = name
p = Person()
a. TypeError: init() missing 1 required positional argument
b. AttributeError: ‘Person’ object has no attribute ‘name’
c. No error
d. ValueError: too many values to unpack
146. What is the error in the following code:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
r = Rectangle(5)
a. TypeError: init() missing 1 required positional argument
b. AttributeError: ‘Rectangle’ object has no attribute ‘width’
c. No error
d. ValueError: too many values to unpack
147. What is the error in the following code:
class Circle:
def __init__(self, radius):
self.radius = radius
c = Circle(5)
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
148. What is the error in the following code:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
e = Employee("John", role="Manager")
a. TypeError: init() got an unexpected keyword argument ‘role’
b. AttributeError: ‘Employee’ object has no attribute ‘role’
c. No error
d. ValueError: too many values to unpack
149. What is the error in the following code:
class Car:
def start(self):
print("Engine started")
c = Car()
c.stop()
a. AttributeError: ‘Car’ object has no attribute ‘stop’
b. TypeError: ‘Car’ object is not callable
c. No error
d. ValueError: name ‘stop’ is not defined
150. What is the error in the following code:
class Shape:
def __init__(self, name):
self.name = name
s = Shape("Square")
print(s.area())
a. AttributeError: ‘Shape’ object has no attribute ‘area’
b. TypeError: ‘NoneType’ object is not callable
c. No error
d. ValueError: name ‘area’ is not defined
151. What is the error in the following code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(2, 3)
print(p.z)
a. AttributeError: ‘Point’ object has no attribute ‘z’
b. TypeError: ‘Point’ object is not callable
c. No error
d. ValueError: name ‘z’ is not defined
152. What is the error in the following code:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
d = Dog(name="Buddy", age=3, color="Brown")
a. TypeError: init() got an unexpected keyword argument ‘color’
b. AttributeError: ‘Dog’ object has no attribute ‘color’
c. No error
d. ValueError: too many values to unpack
153. What is a class method in Python?
a. A method that can only be called on instances of a class
b. A method that is defined within a class
c. A method that is called on the class itself rather than an instance
d. A method that can only be called on abstract classes
154. How is a class method decorated in Python?
a. @classmethod
b. @staticmethod
c. @instance_method
d. None of the above
155. What is the first parameter of a class method conventionally
named in Python?
a. self c. this
b. cls d. class
156. What can a class method access in Python?
a. Only instance variables
b. Only other class methods
c. Both class variables and instance variables
d. Only private variables
157. How is a class method called in Python?
a. MyClass.method()
b. self.method()
c. cls.method()
d. method()
158. What is the purpose of a class 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. None of the above
159. Can a class method access instance variables directly?
a. Yes, always
b. No, never
c. Yes, but only if the instance is passed as an argument
d. Only if the instance is declared as a class variable
160. In Python, can a class method be called on an instance of the class?
a. Yes, always
b. No, never
c. Yes, but only if explicitly allowed
d. Only if the instance is created using `__new__` method
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
163. What is the purpose of inheritance in Python OOPS
programming?
a. To create new classes with enhanced functionality
b. To provide code reusability
c. To establish parent-child relationships between classes
d. All of the above
164. In Python, which keyword is used to create a child class?
a. class
b. child
c. subclass
d. extend
165. Which type of inheritance allows a class to inherit properties from
multiple parent classes?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
166. Which type of inheritance allows a class to inherit properties from
its immediate parent class only?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
167. In Python, if a child class inherits from multiple parent classes
that have a method with the same name, which method will be
executed when calling that method from the child class?
a. Method of the first parent class
b. Method of the last parent class
c. All methods will be executed
d. It will throw an error
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
169. Which type of inheritance is implemented by creating a chain of
parent-child relationships?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
171. Which type of inheritance combines multiple types of inheritance?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
173. Which inheritance type allows a class to inherit properties from
both a parent class and a grandparent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
175. Which type of inheritance is used when a class inherits from
another class, which in turn inherits from another class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
176. In Python, can a child class inherit properties from multiple
parent classes with the same method name?
a. Yes, and it will execute all methods with the same name.
b. No, Python does not allow multiple methods with the same name
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.
177. Which type of inheritance is most commonly used in Python
OOPS programming?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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.
179. Which type of inheritance allows a class to inherit properties from
multiple parent classes, but not the methods?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
180. In Python, can a child class inherit from a parent class that is
defined in a different module?
a. Yes, as long as the module is imported correctly
b. No, Python does not support inheritance across different modules
c. Only if the child class is also defined in the same module as the
parent class
d. It depends on the specific implementation of the child class and
module structure
181. What is instantiation in terms of OOP terminology?
a. Deleting an instance of class
b. Creating an instance of class
c. Modifying an instance of class
d. Copying an instance of class
182. In Python, which method is automatically called when creating an
instance of a child class?
a. __init__ c. __create__
b. __new__ d. __construct__
183. Which type of inheritance is used when a class inherits properties
from multiple parent classes, and all parent classes inherit from a
common grandparent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
184. In Python, can a child class inherit properties from multiple
parent classes with conflicting attribute names?
a. Yes, and the child class will have access to all conflicting
attributes
b. No, Python does not allow conflicting attribute names 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 attribute resolution order
185. Which keyword is used to check if a class is a subclass of another
class?
a. subclass c. issubclass
b. extends d. inherits
186. In Python, can a child class inherit from a parent class that is
defined as a child class of another parent class?
a. Yes, as long as the inheritance chain is defined correctly
b. No, Python does not support inheritance of parent classes from
child classes
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 inheritance chain
187. Which type of inheritance allows a class to inherit properties from
a parent class, which in turn also inherits from another parent
class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
188. In Python, can a child class override the __init__() method of
the parent class?
a. Yes, and it will execute the child class __init__() method instead
of the parent class __init__() method
b. No, the __init__() method cannot be overridden in child classes
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
the method resolution order
189. Which type of inheritance allows a class to inherit properties from
multiple parent classes, and each parent class can have its own
parent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
191. Which type of inheritance allows a class to inherit properties from
multiple parent classes, but not the attributes?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
193. Which inheritance type allows a class to inherit properties from a
parent class, but not the methods?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
195. Which keyword is used to inherit properties from a parent class in
Python?
a. inherits c. extend
b. inheriting d. super
196. In Python, can a child class inherit a private method from the
parent class?
a. Yes, child classes can inherit and access private methods of the
parent class
b. No, child classes cannot inherit private methods of the parent
class
c. Only if the private methods are marked as “protected” instead of
“private”
d. It depends on the specific implementation of the child class and
the access specifiers
197. Which type of inheritance allows a class to inherit properties from
a parent class, which in turn also inherits properties from another
parent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
199. Which type of inheritance allows a class to inherit properties from
a parent class, which in turn inherits properties from its own
parent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
200. In Python, can a child class inherit properties from multiple
parent classes with different attribute names?
a. Yes, child classes can inherit properties from multiple parent
classes with different attribute names
b. No, Python does not allow inheritance of properties with different
attribute names
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
the attribute resolution order
201. Which inheritance type allows a class to inherit properties from a
parent class, which in turn also inherits properties from its own
parent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
202. In Python, can a child class inherit from multiple parent classes
with conflicting attributes?
a. Yes, and it will result in an ambiguity error
b. No, Python does not allow conflicting attributes in an inheritance
chain
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
the attribute resolution order
203. Which type of inheritance allows a class to inherit properties from
multiple parent classes, but not the methods?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
204. In Python, can a child class inherit properties from multiple
parent classes with conflicting methods?
a. Yes, and it will execute all methods with the same name
b. No, Python does not allow conflicting methods in an inheritance
chain
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
205. Which type of inheritance allows a class to inherit properties from
both a parent class and a grandparent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
206. In Python, can a child class access protected variables and
methods of the parent class?
a. Yes, child classes have full access to all parent class members,
including protected members
b. No, child classes cannot access protected 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 specific implementation of the child class and
the access specifiers
207. Which type of inheritance is used when a class inherits properties
from multiple parent classes, and each parent class can have its
own parent class?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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.
209. Which type of inheritance allows a class to inherit properties from
multiple parent classes, but not the attributes?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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
211. Which type of inheritance allows a class to inherit properties from
a parent class, but not the methods?
a. Single inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Hybrid inheritance
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.
213. What is polymorphism in Python?
a. It is the ability of an object to take on many forms
b. It is a type of data structure in Python
c. It is a method of error handling in Python
d. It is a sorting algorithm in Python
214. Which keyword is used to implement polymorphism in Python?
a. polymorphism
b. var
c. def
d. None of the above
215. What is method overriding in Python?
a. It is the ability to define a method in a child class that is already
defined in the parent class
b. It is the ability to define a variable in a child class that is already
defined in the parent class
c. It is a type of error handling in Python
d. It is a type of loop in Python
216. Which of the following is an example of polymorphism in Python?
a. Inheritance
b. Encapsulation
c. Method overloading
d. Method overriding
217. How can polymorphism be achieved in Python?
a. By using inheritance and method overriding
b. By using encapsulation and method overloading
c. By using loops and conditionals in Python
d. By using the polymorphism keyword in Python
218. Which of the following statements is true about polymorphism in
Python?
a. It improves code reusability and maintainability
b. It can only be achieved through encapsulation
c. It is a feature specific to Python programming language
d. It is a type of data structure in Python
219. What is method overloading in Python?
a. It is the ability to define multiple methods with the same name
but different parameters.
b. It is the ability to define multiple methods with different names
but the same parameters.
c. It is a type of error handling in Python.
d. It is a type of loop in Python.
220. Which concept in object-oriented programming does
polymorphism closely relate to?
a. Inheritance c. Abstraction
b. Encapsulation d. Composition
221. How does polymorphism contribute to code flexibility in Python?
a. It allows for dynamic method invocation at runtime
b. It automatically handles errors and exceptions
c. It speeds up the execution of the code
d. It restricts the number of available methods and variables
222. Which of the following is an advantage of using polymorphism in
Python?
a. It allows for more efficient memory allocation
b. It facilitates easier debugging of code
c. It discourages code reuse
d. It increases code complexity
223. What is an example of polymorphism in Python?
a. A parent class defining a method that is overridden by a child
class
b. Using multiple inheritance in Python
c. Encapsulating data within a class
d. Creating a list of different data types in Python
224. Which of the following is not a type of polymorphism in Python?
a. Compile-time polymorphism
b. Runtime polymorphism
c. Operator polymorphism
d. Static polymorphism
225. What is compile-time polymorphism in Python?
a. It is a type of polymorphism that is resolved at compile-time
b. It is a type of polymorphism that is resolved at runtime
c. It is a type of polymorphism that occurs during the execution of a
program
d. It is a type of error handling in Python
226. What is runtime polymorphism in Python?
a. It is a type of polymorphism that is resolved at compile-time
b. It is a type of polymorphism that is resolved at runtime
c. It is a type of polymorphism that occurs during the execution of a
program
d. It is a type of loop in Python
227. What is the difference between method overloading and method
overriding?
a. Method overloading allows defining multiple methods with the
same name but different parameters, while method overriding
allows redefining a method in the child class that is already
defined in the parent class.
b. Method overloading allows redefining a method in the child class
that is already defined in the parent class, while method
overriding allows defining multiple methods with the same name
but different parameters.
c. Method overloading and method overriding are the same concept
in Python.
d. Method overloading and method overriding are not related to
polymorphism.
228. What are decorators in Python?
a. They are special functions that modify the behavior of other
functions or classes
b. They are decorators used to style the user interface of a Python
application
c. They are decorators used to add decorative elements to a Python
program’s output
d. They are decorators used to create visual effects in Python
graphics
229. What symbol is used to apply a decorator to a function or class in
Python?
a. @ c. #
b. $ d. !
230. What is the purpose of using decorators in Python?
a. To add extra functionality to existing functions or classes
b. To change the name of a function or class
c. To remove certain functionality from a function or class
d. To make a function or class inaccessible
231. Which of the following statements is true about decorators?
a. They can only be used with functions, not classes
b. They can only modify the behavior of a function, not its
arguments or return values
c. They can be nested within each other
d. They can only be defined within a class, not at the module level
232. How can decorators be used to implement access control in
Python?
a. Decorators can be used to restrict access to certain functions or
classes based on user credentials
b. Decorators can be used to add additional security measures to a
Python program
c. Decorators can be used to modify the behavior of the Python
interpreter itself
d. Decorators cannot be used for access control purposes in Python
233. Which built-in Python function is used to define a decorator?
a. decorate()
b. decorator()
c. functools()
d. functools.wraps()
234. What is the role of the functools.wraps() function when
defining a decorator?
a. It is used to add additional functionality to the decorated function
or class
b. It is used to wrap the original function or class with the
decorator’s code
c. It is used to preserve the original function or class’s metadata and
docstring
d. It is used to remove the original function or class and replace it
with the decorator
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
236. Can a decorator be applied to a class method in Python?
a. No, decorators can only be applied to functions
b. Yes, decorators can be applied to both functions and class
methods
c. Yes, but only if the class method is defined as a staticmethod
d. No, decorators are not supported for class methods in Python
237. What is the order of execution when multiple decorators are
applied to a function?
a. The decorators are applied in reverse order, from outermost to
innermost
b. The decorators are applied in random order
c. The decorators are applied simultaneously
d. The decorators are applied in the order they are defined
238. Is it possible to remove a decorator from a decorated function or
class?
a. Yes, it is possible to remove a decorator by redefining the
function or class without applying the decorator.
b. No, decorators cannot be removed once applied.
c. Yes, decorators can be removed using the @remove syntax.
d. No, decorators are permanent modifications to the function or
class.
239. Can a decorator modify the arguments passed to a function?
a. Yes, a decorator can modify the arguments passed to a function
b. No, decorators cannot modify the arguments of a function
c. Yes, but only if the decorator is applied to a class method
d. No, decorators can only modify the return value of a function
240. Which of the following is not a commonly used decorator in
Python?
a. @property c. @abstractmethod
b. @staticmethod d. @override
241. Can a decorator be defined using a class instead of a function?
a. Yes, decorators can be defined using either a class or a function
b. No, decorators can only be defined using a function
c. Yes, but only if the class is a subclass of a predefined decorator
class
d. No, decorators can only be defined using a class, not a function
242. What is the purpose of using decorators in the context of method
chaining?
a. Decorators can be used to add additional methods to a class
during runtime
b. Decorators can be used to override the behavior of existing
methods in a class
c. Decorators can be used to modify the input or output of a method
in a chain
d. Decorators are not applicable to method chaining in Python
243. Which of the following keywords is used to define a decorator in
Python?
a. decorator c. class
b. def d. decorate
244. Can a decorator be applied to a class in Python?
a. Yes, decorators can be applied to both functions and classes
b. No, decorators can only be applied to functions in Python
c. Yes, but only if the class is defined as a staticmethod
d. No, decorators are not supported for classes in Python
245. What is the purpose of using decorators in exception handling?
a. Decorators can be used to automatically catch and handle
exceptions thrown by a function or method.
b. Decorators can be used to suppress all exceptions thrown by a
function or method.
c. Decorators cannot be used for exception handling in Python.
d. Decorators can be used to throw additional exceptions based on
certain conditions.
246. Can a decorator modify the return value of a function?
a. Yes, a decorator can modify the return value of a function
b. No, decorators cannot modify the return value of a function
c. Yes, but only if the decorator is applied to a class method
d. No, decorators can only modify the arguments of a function
247. How can decorators be used to measure the execution time of a
function in Python?
a. Decorators can be applied to a function to record the start and end
timestamps and calculate the elapsed time
b. Decorators can be used to display a progress bar indicating the
time taken by a function to complete
c. Decorators can be used to limit the execution time of a function
to a specific duration
d. Decorators cannot be used to measure the execution time of a
function in Python
248. What is a static method in Python?
a. A method that can only be called on instances of a class
b. A method that is defined within a class
c. A method that is called on the class itself rather than an instance
d. A method that can only be called on abstract classes
249. How is a static method decorated in Python?
a. @classmethod
b. @staticmethod
c. @instance_method
d. None of the above
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
1 a 51 a 101 a 151 a 201 c
2 d 52 c 102 c 152 a 202 d
3 d 53 a 103 a 153 c 203 b
4 a 54 d 104 a 154 a 204 d
5 a 55 a 105 c 155 b 205 b
6 b 56 c 106 a 156 c 206 a
7 a 57 d 107 c 157 c 207 d
8 b 58 a 108 d 158 b 208 a
9 a 59 a 109 c 159 b 209 b
10 a 60 b 110 b 160 c 210 b
11 c 61 b 111 a 161 c 211 a
12 c 62 b 112 b 162 c 212 a
13 b 63 b 113 b 163 d 213 a
14 a 64 d 114 b 164 a 214 d
15 a 65 a 115 d 165 b 215 a
16 a 66 a 116 c 166 a 216 d
17 a 67 a 117 a 167 b 217 a
18 a 68 b 118 a 168 a 218 a
19 c 69 d 119 a 169 c 219 a
20 a 70 b 120 b 170 a 220 a
21 a 71 b 121 b 171 d 221 a
22 a 72 b 122 a 172 b 222 b
23 a 73 a 123 a 173 b 223 a
24 a 74 a 124 b 174 b 224 c
25 b 75 b 125 b 175 c 225 a
26 a 76 a 126 b 176 a 226 b
27 b 77 b 127 b 177 a 227 a
28 a 78 d 128 d 178 d 228 a
29 a 79 a 129 a 179 b 229 a
30 a 80 a 130 a 180 a 230 a
31 d 81 b 131 d 181 b 231 c
32 c 82 c 132 b 182 a 232 a
33 a 83 a 133 b 183 d 233 c
34 a 84 a 134 b 184 d 234 c
35 b 85 b 135 a 185 c 235 d
36 d 86 b 136 b 186 a 236 b
37 c 87 d 137 a 187 b 237 a
38 d 88 c 138 a 188 a 238 b
39 c 89 b 139 a 189 d 239 a
40 a 90 b 140 a 190 a 240 d
41 a 91 b 141 a 191 b 241 a
42 a 92 a 142 a 192 b 242 c
43 c 93 b 143 b 193 a 243 b
44 b 94 c 144 a 194 a 244 a
45 b 95 d 145 a 195 c 245 a
46 a 96 a 146 a 196 b 246 a
47 a 97 b 147 a 197 b 247 a
48 a 98 c 148 a 198 a 248 c
49 a 99 b 149 a 199 c 249 b
50 b 100 b 150 a 200 a 250 d
CHAPTER 15
Graphical User Interfaces in Python
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.
Multiple choice questions
1. Which of the following libraries is a commonly used GUI toolkit
for Python?
a. Pandas c. Matplotlib
b. Tkinter d. Requests
2. What is the primary purpose of a widget in a GUI?
a. To perform complex mathematical operations
b. To manage layout and design
c. To create database connections
d. To represent interactive elements
3. Which method is used in Tkinter to position widgets in a grid-
based layout?
a. pack() c. grid()
b. place() d. align()
4. Which Tkinter widget is used to display text in multiple lines?
a. Label c. Entry
b. Text d. Message
5. What method is used to add an item to a ListBox widget in
Tkinter?
a. append() c. insert()
b. add_item() d. add()
6. Which module needs to be imported to use PyQt5’s QtWidgets?
a. PyQt5.QtWidgets
b. PyQt5.GUI
c. PyQt5.Widgets
d. PyQt5.UX
7. How can you connect a signal to a slot in PyQt?
a. Using the connect() method
b. Using the signal_slot() function
c. Using the bind() method
d. Using the on() function
8. Which file format is used to define the GUI layout in Kivy?
a. .kv c. .kivy
b. .gui d. .xml
9. In Kivy, which property is used to specify the color of a widget?
a. foreground_color
b. text_color
c. color
d. display_color
10. Which module is typically used for creating graphical user
interfaces in Python?
a. tkinter c. shutil
b. os d. re
11. Which module in JPython is used to create graphical user
interfaces?
a. tkinter
b. pygame
c. matplotlib
d. numpy
12. JPython is a version of which programming language?
a. Java c. C++
b. Python d. JavaScript
13. Which widget in tkinter is used to create a button?
a. Label c. Button
b. Entry d. Frame
14. What is the main function used to create a GUI window in tkinter?
a. main() c. app()
b. window() d. Tk()
15. How can you set the size of a tkinter GUI window?
a. setSize() c. setDimensions()
b. resize() d. geometry()
16. What is the purpose of the pack() method in tkinter?
a. Set the position of the widget
b. Add the widget to the parent window
c. Change the color of the widget
d. Resize the widget
17. Which module is used to display messages or prompts to the user
in tkinter?
a. tkinter.messagebox
b. tkinter.dialog
c. tkinter.prompt
d. tkinter.inputbox
18. How can you bind a function to a button click event in tkinter?
a. bindClick() c. bind()
b. onClick() d. addEventListener()
19. What function is used to get user input from an Entry widget in
tkinter?
a. getValue() c. get()
b. getText() d. input()
20. Which widget is used to display static text in tkinter?
a. Text c. Label
b. Entry d. Button
21. How can you change the background color of a tkinter widget?
a. setBackgroundColor()
b. setBgColor()
c. setBackground()
d. configure()
22. What layout manager is used by default in tkinter?
a. GridLayout c. FlowLayout
b. BorderLayout d. Pack
23. Which function can be used to terminate a tkinter GUI
application?
a. exit() c. destroy()
b. terminate() d. stop()
24. What is the purpose of the Canvas widget in tkinter?
a. To display images
b. To create custom graphics
c. To draw shapes
d. To play videos
25. Which method is used to set the font of a tkinter widget?
a. setFont() c. setStyle()
b. configure() d. setFontFamily()
26. What does the mainloop() function do in tkinter?
a. Continuously updates the GUI
b. Starts the GUI application
c. Handles user input
d. Closes the GUI window
27. Which widget is used to create a drop-down menu in tkinter?
a. Menu c. SelectBox
b. Dropdown d. Combobox
28. How can you align widgets vertically in tkinter?
a. HBox c. Grid
b. VBox d. StackPanel
29. Which function is used to make a tkinter window resizable?
a. makeResizable() c. resizable()
b. setResizable() d. setResize()
30. What is the purpose of the Grid layout manager in tkinter?
a. Align widgets horizontally
b. Align widgets vertically
c. Arrange widgets in a grid-like structure
d. Stack widgets on top of each other
31. Which widget is used to create a checkbox in tkinter?
a. CheckButton c. ToggleButton
b. CheckBox d. OptionButton
32. How can you change the title of a tkinter window?
a. setTitle() c. setWindowTitle()
b. name() d. title()
33. Which function is used to set the visibility of a widget in tkinter?
a. setVisibility() c. setVisible()
b. show() d. pack()
34. What is the purpose of the Scale widget in tkinter?
a. To display images
b. To create progress bars
c. To select a value from a range
d. To play audio files
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
40. What event is triggered when a button is clicked in tkinter?
a. onClick c. onButtonPress
b. onAction d. <Button-1>
41. How can you change the size of a font in tkinter?
a. setFontSize() c. fontSize()
b. configure() d. setFont()
42. Which widget is used to create a radio button in tkinter?
a. Radiobutton c. ToggleButton
b. RadioButton d. OptionButton
43. What is the purpose of the Message widget in tkinter?
a. To display error messages
b. To display informative messages
c. To display warning messages
d. To display multi-line text
44. How can you set the padding of a tkinter widget?
a. setPadding() c. setMargin()
b. configure() d. padx() and pady()
45. Which function is used to display a file dialog in tkinter?
a. showDialog() c. openDialog()
b. fileDialog() d. askopenfilename()
46. What is the purpose of the Spinbox widget in tkinter?
a. To display images
b. To create progress bars
c. To select a value from a range
d. To play audio files
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>
49. What is the purpose of the Notebook widget in tkinter?
a. To display multiple tabs
b. To create notebooks
c. To organize widgets in a notebook-like structure
d. To open multiple files
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()
52. What is the purpose of the PhotoImage widget in tkinter?
a. To display images
b. To create image galleries
c. To capture images from a camera
d. To play videos
53. How can you set the border color of a tkinter widget?
a. setBorderColor()
b. border()
c. configure()
d. bdColor()
54. Which widget is used to create a progress bar in tkinter?
a. setProgressBar c. Scale
b. Progress d. Progressbar
55. How can you change the font weight of a tkinter widget?
a. setFontWeight() c. setWeight()
b. configure() d. fontWeight()
56. What is the purpose of the Toplevel widget in tkinter?
a. To display popup windows
b. To create top-level windows
c. To organize child widgets
d. To create dialog boxes
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
66. Which method is used to display a message box in tkinter?
a. show_message_box()
b. display_message_box()
c. messagebox()
d. message_box()
67. How can you add an image to a tkinter GUI application?
a. Using the add_image() method
b. Using the insert_image() method
c. Using the image() widget
d. Using the PhotoImage() class
68. Which geometry manager is typically used to arrange widgets in
tkinter?
a. pack() c. place()
b. grid() d. layout()
69. How can you set the title of a tkinter GUI window?
a. Using the set_title() method
b. Using the configure_title() method
c. Using the title() method
d. Using the window_title() method
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
72. How can you change the font of a tkinter widget?
a. using the change_font() method
b. using the set_font() method
c. using the configure() method
d. using the font() method
73. Which module allows you to create a file dialog in tkinter?
a. filedialog c. filepicker
b. dialogbox d. dialog
74. How can you set the background color of a tkinter widget?
a. using the set_bgcolor() method
b. using the configure() method
c. using the set_background() method
d. using the bg() method
75. How can you create a check button widget in tkinter?
a. using the create_checkbox() method
b. using the check_button() method
c. using the Checkbox() widget
d. using the Checkbutton() widget
76. What is the purpose of a scroll bar in tkinter?
a. To scroll through a large amount of text or data
b. To change the color of the GUI
c. To display images
d. To add a border around widgets
77. How can you create a radio button widget in tkinter?
a. using the create_radiobutton() method
b. using the radio_button() method
c. using the Radiobutton() widget
d. using the RadioButton() widget
78. Which method is used to create a canvas widget in tkinter?
a. create_canvas() c. Canvas()
b. custom_canvas() d. add_canvas()
79. What is the purpose of a canvas widget in tkinter?
a. To display graphics and images
b. To play audio files
c. To create buttons and labels
d. To display text and messages
80. How can you change the size of a tkinter window?
a. Using the resize() method
b. Using the configure() method
c. Using the set_size() method
d. Using the window_size() method
81. Which method is used to create a listbox widget in tkinter?
a. create_listbox()
b. custom_listbox()
c. Listbox()
d. add_listbox()
82. What is the purpose of a listbox widget in tkinter?
a. To display a list of items for selection
b. To display images
c. To play videos
d. To change the font of the GUI
83. Which method is used to create a progressbar widget in tkinter?
a. create_progressbar()
b. custom_progressbar()
c. ProgressBar()
d. add_progressbar()
84. How can you create a spinbox widget in tkinter?
a. using the create_spinbox() method
b. using the spin_button() method
c. using the Spinbox() widget
d. using the SpinButton() widget
85. What is the purpose of a spinbox widget in tkinter?
a. To select a value from a range of predefined values
b. To play audio files
c. To change the color of the GUI
d. To add buttons to the GUI
86. Which method is used to create a dropdown menu in tkinter?
a. create_dropdown_menu()
b. custom_dropdown_menu()
c. DropdownMenu()
d. OptionMenu()
87. What is the purpose of a dropdown menu in tkinter?
a. To provide a list of choices for selection
b. To change the font of the GUI
c. To display images
d. To resize the window
88. What is the purpose of a message widget in tkinter?
a. To display a message or alert
b. To display images
c. To play videos
d. To change the background color of the GUI
89. Which method is used to create a scale widget in tkinter?
a. create_scale() c. Scale()
b. custom_scale() d. add_scale()
90. What is the purpose of a scale widget in tkinter?
a. To select a value from a range by sliding a slider
b. To change the font of the GUI
c. To display images
d. To add buttons to the GUI
91. How can you create a tabbed widget in tkinter?
a. using the create_tabbed_widget() method
b. using the tab_widget() method
c. using the TabWidget() widget
d. using the Notebook() widget
92. What is the purpose of a tabbed widget in tkinter?
a. To organize content into multiple tabs
b. To display images
c. To play audio files
d. To resize the window
93. Which method is used to create a treeview widget in tkinter?
a. create_treeview()
b. custom_treeview()
c. TreeView()
d. add_treeview()
94. What is the purpose of a treeview widget in tkinter?
a. To display hierarchical data in a tree-like structure
b. To change the color of the GUI
c. To display images
d. To add buttons to the GUI
95. How can you create a tooltip for a tkinter widget?
a. Using the create_tooltip() method
b. Using the tooltip() method
c. Using the ToolTip() class
d. Using the add_tooltip() method
96. How can you create a combobox widget in tkinter?
a. Using the create_combobox() method
b. Using the combo_button() method
c. Using the Combobox() widget
d. Using the ComboBox() widget
97. What is the purpose of a combobox widget in tkinter?
a. To provide a dropdown with a text entry field
b. To change the font of the GUI
c. To play audio files
d. To add buttons to the GUI
98. Which method is used to create a frame widget in tkinter?
a. create_frame()
b. custom_frame()
c. Frame()
d. add_frame()
99. What is the purpose of a frame widget in tkinter?
a. To group and organize other widgets
b. To display images
c. To play videos
d. To change the background color of the GUI
100. How can you create a progressbar widget in tkinter?
a. Using the create_progressbar() method
b. Using the custom_progressbar() method
c. Using the ProgressBar() widget
d. Using the add_progressbar() method
101. Which method is used to create a notebook widget in tkinter?
a. create_notebook()
b. custom_notebook()
c. Notebook()
d. add_notebook()
102. What is the purpose of a notebook widget in tkinter?
a. To organize content into multiple tabs
b. To display images
c. To play audio files
d. To add a border around widgets
103. Which method is used to create a radiobutton widget in tkinter?
a. create_radiobutton()
b. custom_radiobutton()
c. RadioButton()
d. add_radiobutton()
104. What is the purpose of a radiobutton widget in tkinter?
a. To select a single option from a list of options
b. To change the color of the GUI
c. To display images
d. To resize the window
105. How can you create a listbox widget in tkinter?
a. using the create_listbox() method
b. using the list_button() method
c. using the ListBox() widget
d. using the Listbox() widget
106. Which method is used to create a message widget in tkinter?
a. create_message()
b. custom_message()
c. Message()
d. add_message()
107. What is the purpose of a progressbar widget in tkinter?
a. To show the progress of a task
b. To display images
c. To change the font of the GUI
d. To resize the window
108. Which method is used to create a combobox widget in tkinter?
a. create_combobox()
b. custom_combobox()
c. Combobox()
d. add_combobox()
109. How can you create a radiobutton widget in tkinter?
a. using the create_radiobutton() method
b. using the radio_button() method
c. using the Radiobutton() widget
d. using the RadioButton() widget
110. How can you create a message widget in tkinter?
a. using the create_message() method
b. using the message_box() method
c. using the Message() widget
d. using the add_message() widget
111. Which method is used to create a new frame in wxPython?
a. wx.NewWindow()
b. wx.NewFrame()
c. wx.Frame()
d. wx.CreateFrame()
112. What is the purpose of the wxPython library?
a. To create command-line applications
b. To create web applications
c. To create graphical user interfaces
d. To create networking applications
113. How do you bind an event handler function to a button in
wxPython?
a. Using the SetEvent() method
b. Using the Connect() method
c. Using the Bind() method
d. Using the AddEventHandler() method
114. Which widget is used to display an image in wxPython?
a. wx.TextCtrl c. wx.Bitmap
b. wx.Button d. wx.ListCtrl
115. What is the purpose of the Sizer class in wxPython?
a. To manage the layout of widgets in a frame
b. To handle user input events
c. To store and retrieve data in a database
d. To handle networking operations
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
117. Which method is used to display a dialog box with a message in
wxPython?
a. ShowInfoDialog()
b. DisplayMessageBox()
c. ShowMessageDialog()
d. ShowDialogBox()
118. How can you create a menu bar in wxPython?
a. Using the CreateMenuBar() method
b. Using the SetMenuBar() method
c. Using the AddMenuBar() method
d. Using the MakeMenuBar() method
119. What is the purpose of the wx.EVT_BUTTON event in wxPython?
a. To handle keyboard events
b. To handle mouse events
c. To handle button click events
d. To handle window close events
120. How can you resize a window programmatically in wxPython?
a. Using the Resize() method
b. Using the SetSize() method
c. Using the AdjustSize() method
d. Using the ChangeSize() method
121. What is an event in Python GUI programming?
a. An automatic message generated by the user
b. A user action or system event triggered by the application
c. A predefined function that handles user interactions
d. A graphical element on the GUI interface
122. Which Python library is commonly used for GUI programming?
a. Tkinter c. Pygame
b. NumPy d. Pandas
123. How can you bind an event to a specific widget in Tkinter?
a. Using the ‘bind()’ method
b. By assigning the event to a variable
c. By using the ‘event.bind()’ function
d. It happens automatically
124. Which method is used to handle a button click event in Tkinter?
a. on_button_click()
b. handle_button_click()
c. button_click_event()
d. command=
125. What does the ‘event.widget’ attribute refer to in Tkinter?
a. The current user’s mouse position
b. The widget associated with the event
c. The event type triggered
d. The parent window of the widget
126. What is the purpose of the ‘event.char’ attribute in Tkinter?
a. It stores the character typed by the user
b. It defines the event type
c. It stores the event time
d. It defines the event coordinates
127. How can you stop the propagation of an event in Tkinter?
a. Using the ‘stop()’ method
b. By setting the ‘event.stopPropagation’ attribute to True
c. By using the ‘event.stop()’ statement
d. It cannot be stopped
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
131. Which method is used to handle a widget resize event in Tkinter?
a. on_resize()
b. handle_resize()
c. resize_event()
d. bind(‘<Configure>’)
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>)
140. Which method is used to handle a window close event in Tkinter?
a. on_window_close()
b. handle_close_event()
c. close_window()
d. protocol(WM_DELETE_WINDOW, handler_function)
141. Which of the following is the recommended naming convention for
a button widget in Python?
a. buttonWidget c. button_widget
b. Button_Widget d. buttonwidget
142. What does the self-parameter represent in widget naming
conventions?
a. The class instance itself
b. The parent widget
c. The child widget
d. The widget’s label
143. Which of the following is a valid widget name in Python?
a. 123Widget c. _widget
b. widget123 d. widget$
144. What is the purpose of using camel case in widget naming
conventions?
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
145. It is recommended to use single underscores (_) as prefix for
private widget names.
a. True b. false
146. Which of the following is a valid widget class name in Python?
a. button c. buttonClass
b. Button d. ButtonClass
147. What is the purpose of using Pascal case in widget naming
conventions?
a. To follow PEP 8 guidelines
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
148. Which of the following is not a recommended naming convention
for a label widget in Python?
a. labelWidget c. label_widget
b. Label_Widget d. labelwidget
149. It is recommended to use double underscores (__) as prefix for
magic widget names.
a. True b. false
150. What is the purpose of using snake case in widget naming
conventions?
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
151. Which of the following is the recommended naming convention for
a checkbox widget in Python?
a. CheckboxWidget
b. Checkbox_Widget
c. checkbox_widget
d. checkboxwidget
152. What is the purpose of using title case in widget naming
conventions?
a. To follow PEP 8 guidelines
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
153. It is recommended to use all lowercase letters for widget names.
a. True b. False
154. Which of the following is a valid widget name in Python?
a. Button-Widget1
b. button-widget-1
c. button_widget_1
d. Button_Widget_1$
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
156. Which of the following is not a recommended naming convention
for a text input widget in Python?
a. TextInputWidget
b. Text_Input_Widget
c. textinput_widget
d. textInputWidget
157. It is recommended to use single underscores (_) as suffix for
widget names.
a. True b. false
158. What is the purpose of using double underscores (__) in widget
names?
a. To indicate a specific type of widget
b. To follow PEP 8 guidelines
c. To differentiate between parent and child widgets
d. It is not a recommended naming convention in Python
159. Which of the following is a valid widget class name in Python?
a. checkbox c. checkboxClass
b. Checkbox d. CheckboxClass
160. What is the purpose of using lowercase letters in widget naming
conventions?
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
161. Which geometry manager is used in Python to control layout?
a. Pack c. Place
b. Grid d. None of above
162. Which method is used to add a widget to a grid layout?
a. add() c. grid()
b. insert() d. put()
163. How do you specify the position of a widget in a grid layout?
a. row and column
b. x and y
c. place()
d. height and width
164. In a grid layout, what happens if a cell is left empty?
a. It creates an empty widget
b. The cell collapses
c. Nothing happens
d. Error
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
166. Which geometry manager is used to place widgets freely at exact
positions?
a. Pack c. Place
b. Grid d. None of above
167. How do you add padding around a widget in a place layout?
a. Use the padx and pady parameters
b. Use the expand parameter
c. Use the fill parameter
d. Use height and width parameters
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
169. Which geometry manager is best suited for creating complex
layouts?
a. Pack c. Place
b. Grid d. All of the above
170. Can you use multiple geometry managers within the same
window?
a. Yes, but only one at a time.
b. No, it is not possible.
c. Yes, you can mix and match.
d. None of the above
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
172. Which method is used to remove a widget from a layout?
a. remove() c. forget()
b. delete() d. pop()
173. How do you create a horizontal spacer using the pack manager?
a. Use the pack() method with the side parameter set to “left”
b. Use the pack() method with the side parameter set to “right”
c. Use the pack() method with the side parameter set to “top”
d. Use the pack() method with the side parameter set to “bottom”
174. Which method is used to adjust the position of a widget in a place
layout?
a. move() c. position()
b. adjust() d. set()
175. How do you specify the expand behavior of a widget in the grid
layout?
a. Set the expand parameter to True
b. Set the fill parameter to “both”
c. Set the sticky parameter to “ns” or “ew”
d. Set the expand parameter to False
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
180. What is the primary advantage of using geometry managers in
Python?
a. Easier code maintenance
b. Improved user experience
c. More control over layout and positioning
d. Improve color and fonts
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)
184. How do you create a check button in Tkinter?
a. check_button = Button(text=”Check”)
b. check_button = Checkbutton(text=”Check”)
c. check_button = Checkbox(text=”Check”)
d. check_button = ToggleButton(text=”Check”)
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)
188. In Tkinter, how do you create a drop-down menu?
a. dropdown = DropdownMenu()
b. dropdown = Menu()
c. dropdown = ComboBox()
d. dropdown = DropMenu()
189. Which method is used to add a new item to a drop-down menu in
Tkinter?
a. add_item() c. add_command()
b. append() d. add_option()
190. How do you create a progress bar in Tkinter?
a. progress_bar = ProgressBar()
b. progress_bar = Progress()
c. progress_bar = tkinter.progressbar()
d. progress_bar = ttk.Progressbar()
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
193. How do you create a resizable window in Tkinter?
a. window = tkinter.Window(resizable=True)
b. window = tkinter.Tk()
c. window = tkinter.Window(resizable=1)
d. window = tkinter.Frame(resizable=True)
194. Which layout manager is most commonly used for arranging GUI
elements in Tkinter?
a. Grid c. Place
b. Pack d. Stack
195. In Tkinter, how do you create a canvas for drawing shapes?
a. canvas = DrawingCanvas()
b. canvas = tkinter.Canvas()
c. canvas = DrawingBoard()
d. canvas = tkinter.DrawingCanvas()
196. Which method is used to draw a rectangle on a canvas in Tkinter?
a. draw_rectangle()
b. create_rectangle()
c. rectangle()
d. add_rectangle()
197. How do you change the background color of a button in Tkinter?
a. button.background = “red”
b. button.bg_color(“red”)
c. button.config(bg=”red”)
d. button.style(bg=”red”)
198. Which widget is used to display images in Tkinter?
a. ImageBox c. ImageViewer
b. ImageFrame d. Label
199. How do you bind an event to a widget in Tkinter?
a. widget.bind(event_type, function)
b. widget.event_bind(event_type, function)
c. bind(widget, event_type, function)
d. bind(event_type, function, widget)
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()
201. How do you create a tooltip for a widget in Tkinter?
a. tooltip.create(widget, text=”Tooltip Text”)
b. tooltip = Tooltip(widget, text=”Tooltip Text”)
c. widget.tooltip(text=”Tooltip Text”)
d. Tooltip.create(widget, text=”Tooltip Text”)
202. How do you set the title of a Tkinter window?
a. window.title = “Window Title”
b. window.configure(title=”Window Title”)
c. window.set_title(“Window Title”)
d. window.set_title = “Window Title”
203. Which of the following could be a potential error when importing
the Tkinter module?
a. ModuleNotFoundError: No module named ‘Tkinter’
b. ImportError: Cannot import module ‘Tkinter’
c. SyntaxError: Unexpected keyword ‘Tkinter’
d. TypeError: Tkinter is not callable
204. What could be the cause of the error “AttributeError:
‘NoneType’ object has no attribute ‘pack’”?
a. Forgetting to instantiate a widget before calling the pack()
method
b. Incorrectly specifying the pack() method arguments
c. Calling the pack() method on a non-widget object
d. Using the wrong version of Python for Tkinter
205. Which of the following could result in the error “NameError:
name ‘Button’ is not defined”?
a. Forgetting to import the Button class from Tkinter
b. Misspelling the word ‘Button’ in the code
c. Not assigning a Button widget to a variable before using it
d. Using the Button class from a different GUI framework
206. What might be a possible reason for the error “TypeError:
int() argument must be a string, a bytes-like
object, or a number, not ‘Tk’”?
a. Attempting to pass a Tkinter widget directly as an argument to
int()
b. Incorrectly converting a Tkinter widget to an integer using int()
c. Using a non-numeric string as an argument to the Tk()
constructor
d. Passing a Tk() instance as an argument to a function that expects
an integer
207. What could be the cause of the error “TclError: unknown
option ‘-size’”?
a. Using an invalid option when configuring a widget
b. Specifying a non-existent Tkinter widget size
c. Missing a required argument when calling the size() method
d. Using an outdated version of Tkinter that does not support the -
size option
208. What might be a possible issue when encountering the error
“AttributeError: ‘Frame’ object has no
attribute ‘grid’”?
a. Using the grid() method on a non-existent Frame object
b. Missing the Tkinter module import
c. Incorrectly calling the grid() method on a widget that does not
support it
d. None of the above
209. What might lead to the error “NameError: name ‘Entry’
is not defined”?
a. Forgetting to import the Entry class from Tkinter
b. Using a deprecated version of Tkinter that doesn’t include the
Entry class
c. Misspelling the word ‘Entry’ in the code
d. None of the above
210. Which module is commonly used for creating graphical user
interfaces (GUIs) in Python?
a. matplotlib c. requests
b. tkinter d. pygame
211. What does the acronym GUI stand for?
a. Graphical User Interface
b. General User Interaction
c. Graphical Utility Integration
d. Global User Interface
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
213. Which function can be used to show an error message dialog in
tkinter?
a. show_warning()
b. show_info()
c. show_error()
d. show_critical()
214. What does the term traceback refer to in Python?
a. A graphical representation of code flow
b. A log of executed functions
c. Information about exceptions and errors
d. A method to track user interactions
215. Which of the following is NOT an error in Python GUI
programming?
a. SyntaxError c. GUIError
b. ValueError d. NameError
216. In tkinter, what method is used to handle the closing of a window?
a. close() c. destroy()
b. exit() d. terminate()
217. What should be done to prevent the GUI from freezing during
time-consuming operations?
a. Use multi-threading
b. Increase the window size
c. Add more RAM
d. Use larger GUI elements
218. Which method is used to add widgets to a tkinter window?
a. add_widget() c. insert_widget()
b. pack() d. place_widget()
219. Which programming language is PySimpleGUI primarily
designed for?
a. JavaScript c. Java
b. Python d. C++
220. What is the primary aim of PySimpleGUI?
a. Web development
b. GUI creation
c. Database management
d. Machine learning
221. Which of the following is NOT a layout type provided by
PySimpleGUI?
a. Column c. Tab
b. Grid d. Frame
222. What is the main advantage of PySimpleGUI?
a. It is only compatible with Windows OS
b. It is complex and difficult to learn
c. It provides a simple interface for creating GUIs
d. It is solely for scientific applications
223. Which method is used to create a button in PySimpleGUI?
a. create_button() c. Button()
b. make_button() d. sg.Button()
224. What does the abbreviation sg stand for in PySimpleGUI?
a. Simple graphics c. System graphics
b. Simple GUI d. System GUI
225. What widget type in PySimpleGUI is used to accept user text
input?
a. InputText c. TextEntry
b. UserInput d. Textbox
226. In PySimpleGUI, which method is used to display a window on the
screen?
a. show_window()
b. display()
c. window.show()
d. sg.Window()
227. Which layout element in PySimpleGUI organizes elements in a
horizontal line?
a. Row c. Frame
b. Column d. Tab
228. What function in PySimpleGUI is used to read and process events
that occur in the GUI?
a. process_events()
b. read_events()
c. sg.event_loop()
d. handle_events()
229. Which PySimpleGUI method is used to set the layout of a
window?
a. set_layout() c. define_layout()
b. window.layout() d. layout()
230. In PySimpleGUI, what method is used to set the title of a window?
a. window.set_title()
b. sg.set_title()
c. set_window_title()
d. window_title()
231. What is the purpose of the sg.theme() function in
PySimpleGUI?
a. To change the programming language used
b. To change the layout structure
c. To set the theme or appearance of the GUI elements
d. To manage data storage
232. Which method in PySimpleGUI is used to create a progress bar?
a. sg.ProgressBar()
b. create_progress_bar()
c. make_progress_bar()
d. ProgressBar()
233. What type of input field in PySimpleGUI is used to select a file
from the filesystem?
a. FileInput c. FileChooser
b. BrowseInput d. FileBrowse()
234. Which function in PySimpleGUI is used to display a popup
message to the user?
a. popup() c. sg.Popup()
b. show_popup() d. display_popup()
235. Which PySimpleGUI element is used to display text in a window?
a. TextElement c. sg.Text()
b. DisplayText d. TextDisplay
236. What layout element in PySimpleGUI is used to add padding
around other elements?
a. Padding
b. Spacer
c. sg.Padding()
d. sg.InputText(padding=())
237. What is the purpose of the sg.Quit() function in
PySimpleGUI?
a. To close the PySimpleGUI library
b. To terminate the Python script
c. To exit the GUI application
d. To prompt a user for confirmation
238. Which method in PySimpleGUI is used to refresh the window and
display changes made to the layout or elements?
a. window.refresh()
b. update_window()
c. refresh_layout()
d. window.refresh() is not required
239. Which programming language is primarily used with PyQt for
creating graphical user interfaces (GUIs)?
a. Java c. Python
b. C++ d. JavaScript
240. What is PyQt?
a. A database management system
b. A machine learning framework
c. A GUI toolkit for Python based on Qt
d. A web development library
241. Which Qt framework forms the foundation of PyQt?
a. Qt Creator c. Qt Widgets
b. Qt Designer d. Qt Quick
242. What function is used to create a PyQt application instance?
a. QtApp() c. QApplication()
b. createApp() d. PyQtApp()
243. Which PyQt method is used to create a push button?
a. createButton() c. QPushButton()
b. makeButton() d. PyQtButton()
244. In PyQt, which module contains the main components for building
the GUI?
a. QtWidgets c. QtGui
b. QtCore d. PyQtBase
245. Which layout manager in PyQt arranges widgets horizontally or
vertically?
a. FlowLayout c. GridBagLayout
b. BoxLayout d. GridLayout
246. What is the purpose of QWidget in PyQt?
a. To create main windows
b. To handle events
c. To represent a single widget
d. To manage layouts
247. Which PyQt function is used to connect a signal to a slot?
a. connect() c. bind()
b. link() d. emit()
248. Which method is used to display a PyQt application’s main
window?
a. show()
b. display()
c. showWindow()
d. displayWindow()
249. Which function can be used to perform arithmetic operations in a
GUI calculator built using Tkinter?
a. add()
b. math.add()
c. calculate()
d. Functions linked to respective buttons
250. What event is often used to trigger the execution of mathematical
operations in a Tkinter-based GUI calculator?
a. on_click() c. command
b. click_event() d. calculate_event()
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 b 51 a 101 c 151 c 201 b
2 d 52 a 102 a 152 d 202 b
3 c 53 c 103 c 153 b 203 a
4 b 54 d 104 a 154 c 204 a
5 a 55 b 105 d 155 b 205 a
6 a 56 b 106 c 156 d 206 c
7 a 57 d 107 a 157 b 207 a
8 a 58 c 108 c 158 c 208 c
9 c 59 a 109 c 159 d 209 a
10 a 60 b 110 c 160 a 210 b
11 a 61 a 111 c 161 b 211 a
12 b 62 a 112 c 162 c 212 d
13 c 63 c 113 c 163 a 213 c
14 d 64 a 114 c 164 c 214 c
15 d 65 d 115 a 165 c 215 c
16 b 66 c 116 a 166 c 216 c
17 a 67 d 117 c 167 a 217 a
18 c 68 a 118 b 168 c 218 b
19 c 69 c 119 c 169 b 219 b
20 c 70 d 120 b 170 c 220 b
21 d 71 a 121 b 171 b 221 b
22 d 72 c 122 a 172 c 222 c
23 c 73 a 123 a 173 a 223 d
24 b 74 d 124 d 174 a 224 b
25 b 75 d 125 b 175 c 225 a
26 a 76 a 126 a 176 c 226 d
27 d 77 c 127 d 177 a 227 a
28 b 78 c 128 b 178 b 228 c
29 c 79 a 129 d 179 a 229 b
30 c 80 b 130 c 180 c 230 a
31 a 81 c 131 d 181 c 231 c
32 d 82 a 132 b 182 a 232 a
33 c 83 d 133 c 183 a 233 c
34 c 84 c 134 a 184 b 234 c
35 d 85 a 135 b 185 c 235 c
36 b 86 d 136 a 186 c 236 c
37 b 87 a 137 c 187 a 237 c
38 d 88 a 138 d 188 b 238 d
39 a 89 c 139 c 189 c 239 c
40 d 90 a 140 d 190 d 240 c
41 b 91 d 141 c 191 b 241 c
42 a 92 a 142 a 192 a 242 c
43 d 93 c 143 b 193 b 243 c
44 d 94 a 144 a 194 a 244 a
45 d 95 c 145 a 195 b 245 b
46 c 96 c 146 d 196 b 246 c
47 c 97 a 147 b 197 c 247 a
48 b 98 c 148 d 198 d 248 a
49 a 99 a 149 b 199 a 249 d
50 c 100 d 150 a 200 b 250 c
CHAPTER 16
Machine Learning with Python
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.
Multiple choice questions
1. What is machine learning?
a. A field of study that gives computers the ability to learn without
being explicitly programmed
b. A method of training computers to carry out specific tasks
c. A way of mimicking human intelligence in machines
d. A technique used to automate manual processes
2. Which of the following is not a type of machine learning?
a. Supervised learning
b. Unsupervised learning
c. Reinforcement learning
d. Pre-emptive learning
3. What is the goal of supervised learning?
a. To predict output values based on input data
b. To discover hidden patterns or structures in data
c. To determine optimal actions based on previous actions and
rewards
d. To classify data into specific categories
4. Which of the following algorithms is commonly used for
supervised classification?
a. Decision trees
b. K-means clustering
c. Reinforcement learning
d. Principal component analysis
5. What is the objective of unsupervised learning?
a. To predict output values based on input data
b. To discover hidden patterns or structures in data
c. To determine optimal actions based on previous actions and
rewards
d. To classify data into specific categories
6. Which of the following algorithms is commonly used for
unsupervised clustering?
a. Linear regression
b. Naive Bayes
c. Support vector machines
d. K-means clustering
7. What is the main difference between supervised and unsupervised
learning?
a. Supervised learning requires labelled data, while unsupervised
learning does not.
b. Supervised learning focuses on classification, while unsupervised
learning focuses on clustering.
c. Supervised learning requires human expertise, while
unsupervised learning is fully automated.
d. Supervised learning is faster than unsupervised learning.
8. What is the purpose of cross-validation in machine learning?
a. To evaluate a model’s performance on unseen data
b. To optimize hyperparameters in a model
c. To improve the training time of a model
d. To generate more training examples
9. What is the concept of feature engineering in machine learning?
a. Creating new features from existing data to improve model
performance
b. Training a model on a large dataset to increase accuracy
c. Selecting the best model based on performance metrics
d. Preprocessing data to remove outliers and missing values
10. Which evaluation metric is commonly used for classification
problems?
a. Mean Squared Error (MSE)
b. Root Mean Squared Error (RMSE)
c. Accuracy
d. R-squared
11. What is overfitting in machine learning?
a. When a model performs well on the training data but poorly on
unseen data
b. When a model performs poorly on the training data but well on
unseen data
c. When a model is undertrained and unable to make accurate
predictions
d. When a model uses too many features, leading to computational
inefficiencies
12. How can overfitting be mitigated?
a. By increasing the complexity of the model
b. By increasing the regularization strength
c. By providing more training examples
d. By decreasing the learning rate
13. What is the purpose of regularization in machine learning?
a. To penalize complex models and prevent overfitting
b. To increase the accuracy of the model by including more features
c. To improve the interpretability of the model
d. To reduce the training time of the model
14. What is the purpose of a validation set in machine learning?
a. To evaluate a model’s performance on unseen data during
training
b. To provide additional training examples to improve model
performance
c. To test the final model’s performance on completely new data
d. To select the best model based on performance metrics
15. What is the difference between bagging and boosting?
a. Bagging combines weak learners into a strong ensemble, while
boosting uses multiple iterations to create a strong learner.
b. Bagging uses multiple iterations to create a strong learner, while
boosting combines weak learners into a strong ensemble.
c. Bagging and boosting are identical techniques with different
names.
d. Bagging and boosting are both unsupervised learning methods.
16. Which of the following is a popular ensemble learning method?
a. Decision tree
b. Linear regression
c. Support vector machine
d. Random forest
17. What is the purpose of feature normalization in machine learning?
a. To reduce the training time of the model
b. To improve the interpretability of the model
c. To standardize input features to a specific range
d. To remove outliers and missing values from the dataset
18. What is dimensionality reduction in machine learning?
a. A technique to transform high-dimensional data into a lower-
dimensional space
b. A method to generate more features from existing data
c. The process of removing outliers from a dataset
d. The process of adjusting the weights in a neural network
19. Which algorithm is commonly used for dimensionality reduction?
a. Logistic regression
b. K-nearest neighbors
c. Principal Component Analysis (PCA)
d. Ridge regression
20. What is the curse of dimensionality in machine learning?
a. The impact of adding more features on model complexity and
performance
b. The difficulty of selecting an appropriate model for a given
problem
c. The presence of outliers in the dataset
d. The imbalance of classes in classification problems
21. What is the importance of data preprocessing in machine
learning?
a. To ensure data is in a suitable format for training a model
b. To reduce the complexity of the model
c. To increase the interpretability of the model
d. To improve the accuracy of the model through feature
engineering
22. Which technique is used to handle missing values in a dataset?
a. Deleting rows with missing values
b. Replacing missing values with the mean or median
c. Creating a new class for missing values
d. Ignoring missing values during model training
23. What is the purpose of regularization in linear regression?
a. To penalize complex models and prevent overfitting
b. To increase the accuracy of the model by including more features
c. To improve the interpretability of the model
d. To reduce the training time of the model
24. Which algorithm is commonly used for linear regression with
multiple features?
a. Decision trees
b. K-means clustering
c. Support vector machines
d. Ridge regression
25. What is the purpose of the bias term in linear regression?
a. To add additional features to the model
b. To balance the weights of different features
c. To adjust the intercept of the linear equation
d. To prevent overfitting of the model
26. Which technique is commonly used to handle categorical variables
in machine learning?
a. One-hot encoding
b. Principal Component Analysis (PCA)
c. Feature scaling
d. Ridge regression
27. What is the purpose of the activation function in a neural
network?
a. To define the number of layers in the network
b. To initialize the weights of the network
c. To introduce non-linearities into the network
d. To determine the learning rate of the network
28. Which algorithm is commonly used for training deep learning
models?
a. Decision trees
b. K-means clustering
c. Backpropagation
d. Support vector machines
29. What is the purpose of batch normalization in deep learning?
a. To prevent overfitting of the model
b. To speed up the training process
c. To normalize input features to a standard range
d. To remove outliers from the dataset
30. Which technique is commonly used to prevent vanishing or
exploding gradients in deep learning?
a. Dropout regularization
b. Batch normalization
c. Feature scaling
d. Early stopping
31. Which algorithm is commonly used for object detection in
computer vision?
a. Linear regression
b. Naive Bayes
c. Support vector machines
d. Convolutional Neural Networks (CNN)
32. What is transfer learning in deep learning?
a. The process of transferring knowledge from one task to another
b. The use of pre-trained models as a starting point for new tasks
c. The creation of a large dataset for model training
d. The process of reducing the dimensionality of input features
33. What is the purpose of Data Augmentation in deep learning?
a. To increase the number of training examples by creating
variations of existing data
b. To remove outliers and missing values from the dataset
c. To generate new features from existing data
d. To reduce the dimensionality of input features
34. What is the purpose of the softmax function in deep learning?
a. To introduce non-linearities into the network
b. To convert raw scores into probability distributions
c. To normalize input features to a standard range
d. To determine the learning rate of the network
35. Which evaluation metric is commonly used for regression
problems?
a. Accuracy
b. Mean Squared Error (MSE)
c. Precision
d. Recall
36. What is the purpose of L1 and L2 regularization in neural
networks?
a. To penalize complex models and prevent overfitting
b. To increase the accuracy of the model by including more features
c. To improve the interpretability of the model
d. To reduce the training time of the model
37. Which technique is commonly used to handle imbalanced classes
in classification problems?
a. Data augmentation
b. Undersampling
c. Oversampling
d. Cluster analysis
38. What is the purpose of dropout regularization in neural networks?
a. To prevent overfitting of the model
b. To speed up the training process
c. To normalize input features to a standard range
d. To remove outliers from the dataset
39. Which algorithm is commonly used for sequence generation tasks
in deep learning?
a. Decision trees
b. K-means clustering
c. Recurrent Neural Networks (RNN)
d. Support vector machines
40. What is the purpose of the attention mechanism in deep learning?
a. To identify important features or regions in input data
b. To balance the weights of different features in the network
c. To prevent overfitting of the model
d. To reduce the dimensionality of input features
41. Which algorithm is commonly used for text classification tasks?
a. Linear regression
b. Naive Bayes
c. Support vector machines
d. Decision trees
42. What is the purpose of word embedding in natural language
processing?
a. To convert words into numerical vectors that can be processed by
algorithms
b. To remove stop words from the text
c. To identify the grammatical structure of a sentence
d. To generate new words based on existing vocabulary
43. Which algorithm is commonly used for sentiment analysis?
a. Linear regression
b. Decision trees
c. Recurrent Neural Networks (RNN)
d. K-means clustering
44. What is the purpose of Long Short-Term Memory (LSTM) in
natural language processing?
a. To identify important features or regions in input data
b. To handle the vanishing gradient problem in recurrent neural
networks
c. To balance the weights of different features in the network
d. To reduce the dimensionality of input features
45. What is the purpose of the BLEU metric in machine translation?
a. To evaluate the fluency of translated sentences
b. To measure the quality of the translation compared to a reference
translation
c. To generate new translations based on existing data
d. To reduce the dimensionality of input features
46. What is reinforcement learning?
a. A method of training computers to carry out specific tasks
b. A technique used to mimic human intelligence in machines
c. A field of study that gives computers the ability to learn without
being explicitly programmed
d. A way of determining optimal actions based on previous actions
and rewards
47. Which algorithm is commonly used for reinforcement learning?
a. Decision trees
b. K-means clustering
c. Q-learning
d. Support vector machines
48. What is the difference between on-policy and off-policy
reinforcement learning?
a. On-policy learning updates the model based on current actions,
while off-policy learning updates the model based on the best
actions.
b. On-policy learning uses a policy to determine actions, while off-
policy learning does not use any policy.
c. On-policy learning uses value functions to evaluate actions, while
off-policy learning uses policy functions.
d. On-policy learning updates the model in real-time, while off-
policy learning updates the model offline.
49. What is exploration-exploitation trade-off in reinforcement
learning?
a. The balance between discovering new actions and exploiting
known actions for rewards.
b. The trade-off between training time and model complexity.
c. The trade-off between the number of features and the model’s
interpretability.
d. The balance between the learning rate and regularization strength.
50. What is the value function in reinforcement learning?
a. A measure of how much future reward can be expected from a
given state or action
b. A function that maps inputs to outputs in a reinforcement
learning model
c. The policy used to determine actions in a reinforcement learning
model
d. A technique used to estimate the model’s performance on unseen
data
51. Which algorithm is commonly used for solving continuous action
space problems in reinforcement learning?
a. Monte Carlo methods
b. Q-learning
c. Policy gradients
d. Deep Q-Networks (DQN)
52. What is the purpose of a reward function in reinforcement
learning?
a. To determine the optimal actions for a given state
b. To provide feedback to the model based on its actions
c. To balance the weights of different features in the network
d. To reduce the training time of the model
53. What is the difference between model-based and model-free
reinforcement learning?
a. Model-based learning builds a model of the environment, while
model-free learning directly interacts with the environment.
b. Model-based learning uses pre-trained models, while model-free
learning trains models from scratch.
c. Model-based learning is fully automated, while model-free
learning requires human expertise.
d. Model-based learning focuses on exploration, while model-free
learning focuses on exploitation.
54. Which algorithm is commonly used for game-playing agents in
reinforcement learning?
a. Decision trees
b. Monte Carlo methods
c. AlphaGo
d. Support vector machines
55. What is deep reinforcement learning?
a. The combination of deep learning and reinforcement learning
techniques
b. The use of pre-trained models as a starting point for
reinforcement learning tasks
c. The use of convolutional neural networks for reinforcement
learning tasks
d. The process of training deep neural networks to play games
56. What is the purpose of the Bellman equation in reinforcement
learning?
a. To update value functions in a model-based learning setup
b. To represent the balance between immediate and future rewards
c. To determine the learning rate of the model
d. To improve the interpretability of the model
57. Which algorithm is commonly used for exploration in
reinforcement learning?
a. Policy gradients
b. Q-learning
c. Monte Carlo methods
d. Greedy algorithm
58. What is the purpose of the Markov Decision Process (MDP) in
reinforcement learning?
a. To model the environment and possible states/actions
b. To generate new training examples for the model
c. To balance the trade-off between exploration and exploitation
d. To introduce non-linearities into the network
59. Which technique is commonly used for credit assignment in
reinforcement learning?
a. Temporal Difference learning
b. Batch normalization
c. Feature scaling
d. Early stopping
60. Which of the following is an example of an application of machine
learning?
a. Detecting fraud in financial transactions
b. Searching for information on the internet
c. Sending emails
d. Creating spreadsheets
61. In healthcare, machine learning can be used for:
a. Predicting earthquake occurrences
b. Recommending personalized treatment plans
c. Designing new drugs
d. Manufacturing medical equipment
62. Which of the following is an example of a natural language
processing (NLP) application in machine learning?
a. Face recognition
b. Sentiment analysis
c. Object detection
d. Weather prediction
63. Machine learning can be used in autonomous vehicles for:
a. Playing music
b. Navigation and obstacle avoidance
c. Maintaining vehicle registration records
d. Unlocking car doors remotely
64. Which of the following industries has not benefited from machine
learning applications?
a. Retail c. Entertainment
b. Agriculture d. Construction
65. Machine learning algorithms can be used to analyze financial data
for:
a. Cooking recipes
b. Predicting stock market trends
c. Choosing the right clothing size
d. Planning vacation itineraries
66. In e-commerce, machine learning can be used for:
a. Reminding users of daily tasks
b. Recommending products based on user preferences
c. Tracking delivery status
d. Signing legal contracts
67. Machine learning techniques can be used in image recognition for:
a. Playing video games
b. Text-to-speech conversion
c. Identifying objects in photographs
d. Creating music
68. Which of the following is an example of a machine learning
application in cybersecurity?
a. Printing documents
b. Analyzing network traffic for detecting anomalies
c. Ordering groceries online
d. Tracking fitness activities
69. Chatbots in customer service applications are powered by:
a. Acoustic wave sensors
b. Machine learning algorithms
c. Fingerprint scanners
d. Barcode readers
70. Machine learning algorithms can be used in social media for:
a. Monitoring heart rate
b. Enhancing photos
c. Recommending friends or connections
d. Calculating body mass index
71. Which of the following is an example of a machine learning
application in energy management?
a. Growing plants indoors
b. Optimizing power grid operations
c. Tracking daily calorie intake
d. Running simulations for weather forecasts
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
74. Machine learning can aid in weather prediction by:
a. Sensing ambient temperature
b. Analyzing historical weather data
c. Measuring blood pressure
d. Tracking international parcel shipments
75. In finance, machine learning algorithms can be used for:
a. Tracking body weight
b. Detecting credit card fraud
c. Playing video games
d. Monitoring sleep patterns
76. Machine learning is used in recommender systems to:
a. Maintain inventory records
b. Provide language translation services
c. Recommend movies, books, or products based on user
preferences
d. Measure internet connection speed
77. Which of the following is an example of a machine learning
application in agriculture?
a. Calculating billing amounts
b. Monitoring heart rate
c. Predicting crop yields
d. Creating digital art
78. Machine learning can be used in gaming for:
a. Scheduling meetings
b. Designing fashion collections
c. Enemy behavior prediction
d. Cooking recipes
79. In education, machine learning can be used for:
a. Analyzing sleep patterns
b. Personalized adaptive learning
c. Tracking shipping records
d. Controlling home appliances
80. Machine learning algorithms can be used in talent recruitment to:
a. Monitor daily steps taken
b. Detect fake news
c. Predict job applicants’ suitability
d. Provide instant language translations
81. In the entertainment industry, machine learning can be used for:
a. Calculating mortgage rates
b. Generating movie trailers
c. Planning bus routes
d. Tracking wildlife migration
82. Machine learning techniques can be used for predictive
maintenance in:
a. Painting walls
b. Repairing appliances
c. Monitoring heart rate
d. Managing city traffic
83. Which of the following is an example of a machine learning
application in logistics and supply chain management?
a. Calculating sales tax
b. Detecting lung diseases
c. Optimizing delivery routes
d. Sketching architectural designs
84. Machine learning can be used in robotics for:
a. Playing musical instruments
b. Detecting emotions
c. Automating repetitive tasks
d. Tracking global currency exchange rates
85. In real estate, machine learning algorithms can be used for:
a. Monitoring blood pressure
b. Valuing properties
c. Creating computer games
d. Tracking space missions
86. Which of the following is an example of a machine learning
application in natural disaster prediction?
a. Tracking package deliveries
b. Detecting lung cancers
c. Predicting earthquakes
d. Recording voice memos
87. Machine learning techniques can be used in quality control to:
a. Monitor daily calorie intake
b. Prevent product defects
c. Calculate international currency exchange rates
d. Design new algorithms
88. Machine learning is used in music streaming services for:
a. Analyzing DNA sequences
b. Recommending personalized playlists
c. Measuring air pollution
d. Identifying plant species
89. Which of the following is an example of a machine learning
application in human resources?
a. Detecting wildfire outbreaks
b. Tracking ocean currents
c. Screening job applicants
d. Sending automated text messages
90. Machine learning can be used in market research for:
a. Drawing geometric shapes
b. Tracking heart rate during exercise
c. Analyzing consumer behavior patterns
d. Controlling smart home devices
91. In sports, machine learning can be used for:
a. Analyzing brain activity
b. Predicting game outcomes
c. Calculating mortgage rates
d. Designing furniture
92. Machine learning algorithms can be used in cybersecurity for:
a. Cooking recipes
b. Identifying malware and viruses
c. Detecting melanoma skin cancer
d. Tracking satellite movements
93. Which of the following is an example of a machine learning
application in digital marketing?
a. Calculating planetary positions
b. Generating personalized advertisements
c. Analyzing sleep patterns
d. Monitoring water quality
94. Machine learning can be used in social sciences for:
a. Analyzing sales data
b. Predicting earthquake magnitudes
c. Studying human behavior patterns
d. Playing video games
95. Machine learning algorithms can be used in language translation
for:
a. Monitoring daily steps taken
b. Calculating BMI
c. Translating text or speech in real-time
d. Analyzing heart rate variability
96. Which of the following is an example of a machine learning
application in environmental monitoring?
a. Designing clothing collections
b. Detecting air pollution levels
c. Predicting stock market trends
d. Controlling smart home devices
97. Machine learning is used in speech recognition applications for:
a. Measuring blood pressure
b. Tracking international parcel shipments
c. Transcribing spoken words into text
d. Playing musical instruments
98. In the legal industry, machine learning can be used for:
a. Analyzing earthquake data
b. Recommending legal strategies
c. Tracking wildlife migration
d. Creating 3D models
99. Machine learning algorithms can be used in sentiment analysis
for:
a. Valuing properties
b. Monitoring sleep patterns
c. Analyzing public opinion on social media
d. Designing fashion collections
100. Which of the following is an example of a machine learning
application in transportation management?
a. Creating computer games
b. Optimizing traffic signal timings
c. Calculating mortgage rates
d. Detecting lung diseases
101. Machine learning can be used in social robotics for:
a. Detecting emotions
b. Analyzing DNA sequences
c. Playing music
d. Monitoring water quality
102. In the insurance industry, machine learning algorithms can be
used for:
a. Tracking space missions
b. Detecting fraudulent claims
c. Predicting volcanic eruptions
d. Recording voice memos
103. Machine learning is used in recommendation systems for:
a. Counting daily steps
b. Generating personalized diet plans
c. Recommending movies or TV shows based on user history
d. Predicting weather conditions
104. Which of the following is an example of a machine learning
application in telecommunications?
a. Analyzing blood glucose levels
b. Predicting cryptocurrency prices
c. Optimizing network performance
d. Calculating planetary positions
105. Machine learning can be used in speech synthesis for:
a. Controlling home appliances
b. Predicting game outcomes
c. Converting text into spoken words
d. Analyzing brain activity
106. In the music industry, machine learning algorithms can be used
for:
a. Analyzing lung capacity
b. Recommending personalized playlists
c. Designing architectural structures
d. Monitoring ocean currents
107. Machine learning is used in cybersecurity for:
a. Tracking wildlife migration
b. Predicting earthquakes
c. Identifying malware or phishing attacks
d. Playing video games
108. Which of the following is an example of a machine learning
application in retail?
a. Analyzing sleep patterns
b. Personalized product recommendations
c. Measuring air pollution levels
d. Studying human behavior patterns
109. Machine learning algorithms can be used in data analysis for:
a. Calculating daily calorie intake
b. Detecting lung diseases
c. Analyzing large datasets to find patterns or insights
d. Designing digital art
110. Which Python library is considered the de facto standard for
machine learning in Python?
a. NumPy c. Pandas
b. TensorFlow d. Matplotlib
111. Which Python library provides high-level APIs for building and
training deep learning models?
a. scikit-learn c. PyTorch
b. Keras d. Theano
112. Which Python library provides data manipulation and analysis
tools, making it suitable for preprocessing and cleaning machine
learning datasets?
a. NumPy c. Pandas
b. scikit-learn d. TensorFlow
113. Which Python library is commonly used for numerical
computations and provides support for multi-dimensional arrays?
a. NumPy c. PyTorch
b. Keras d. Theano
114. Which Python library provides a wide range of machine learning
algorithms and tools for classification, regression, and clustering
tasks?
a. TensorFlow c. Pandas
b. scikit-learn d. Matplotlib
115. Which Python library is primarily used for plotting and
visualization of data?
a. NumPy c. Pandas
b. Keras d. Matplotlib
116. Which Python library provides support for distributed computing
and can be used for large-scale machine learning tasks?
a. TensorFlow c. PySpark
b. scikit-learn d. Matplotlib
117. Which Python library provides extensive support for natural
language processing and text analytics?
a. TensorFlow c. NLTK
b. scikit-learn d. PyTorch
118. Which Python library is commonly used for performing
mathematical operations and functions?
a. NumPy c. Pandas
b. Keras d. Matplotlib
119. Which Python library provides a flexible framework for creating
and training machine learning models?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
120. Which Python library is used for building and training deep
neural networks with dynamic neural networks in Python?
a. NumPy c. PyTorch
b. Keras d. Theano
121. Which Python library provides support for reinforcement
learning algorithms and frameworks?
a. TensorFlow c. PyTorch
b. scikit-learn d. OpenAI Gym
122. Which Python library is commonly used for exploratory data
analysis and building interactive visualizations?
a. NumPy c. Pandas
b. Matplotlib d. Seaborn
123. Which Python library provides tools for parallel computing and
distributed computing for machine learning tasks?
a. TensorFlow c. PyTorch
b. scikit-learn d. Dask
124. Which Python library is used for creating and visualizing decision
trees and random forests?
a. TensorFlow c. Pandas
b. scikit-learn d. Matplotlib
125. Which Python library provides support for feature extraction and
selection in machine learning?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
126. Which Python library is commonly used for time series analysis
and forecasting?
a. Prophet c. Pandas
b. TensorFlow d. Matplotlib
127. Which Python library provides support for natural language
processing and deep learning frameworks for text analytics?
a. TensorFlow c. NLTK
b. scikit-learn d. Gensim
128. Which Python library provides support for unsupervised learning
algorithms such as clustering and dimensionality reduction?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
129. Which Python library provides tools for hyperparameter tuning
and model selection in machine learning?
a. TensorFlow c. Optuna
b. scikit-learn d. Matplotlib
130. Which Python library is commonly used for feature scaling and
preprocessing in machine learning?
a. NumPy c. Pandas
b. scikit-learn d. Matplotlib
131. Which Python library provides support for time series forecasting
and analysis using deep learning models?
a. TensorFlow c. Prophet
b. scikit-learn d. Matplotlib
132. Which Python library is commonly used for image processing and
computer vision tasks in machine learning?
a. OpenCV c. Pandas
b. TensorFlow d. Matplotlib
133. Which Python library provides support for anomaly detection and
outlier detection in machine learning?
a. TensorFlow
b. scikit-learn
c. PyTorch
d. PyOD
134. Which Python library is commonly used for natural language
processing and sentiment analysis tasks?
a. TensorFlow c. NLTK
b. scikit-learn d. Matplotlib
135. Which Python library provides support for time series analysis
and forecasting using statistical models and techniques?
a. TensorFlow c. Pandas
b. scikit-learn d. statsmodels
136. Which Python library is primarily used for deep learning research
and development?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
137. Which Python library provides support for matrix operations and
linear algebra in machine learning?
a. NumPy c. Pandas
b. Keras d. Matplotlib
138. Which Python library provides support for ensemble learning
techniques such as bagging and boosting?
a. TensorFlow c. PyTorch
b. scikit-learn d. XGBoost
139. Which Python library is commonly used for text preprocessing
and feature extraction for natural language processing tasks?
a. TensorFlow c. NLTK
b. scikit-learn d. PyTorch
140. Which Python library provides support for deep learning and
reinforcement learning algorithms?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
141. Which Python library is commonly used for data visualization and
creating interactive plots in machine learning?
a. NumPy c. Pandas
b. Keras d. Plotly
142. Which Python library provides support for Gaussian processes
and Bayesian optimization in machine learning?
a. TensorFlow c. PyTorch
b. scikit-learn d. GPyOpt
143. Which Python library is commonly used for natural language
processing and topic modeling tasks?
a. TensorFlow c. NLTK
b. scikit-learn d. Gensim
144. Which Python library provides support for deep learning research
and development and enables dynamic neural networks in
Python?
a. NumPy c. PyTorch
b. Keras d. Matplotlib
145. Which Python library is commonly used for feature engineering
and feature selection in machine learning?
a. TensorFlow c. PyTorch
b. scikit-learn d. Featuretools
146. Which Python library provides support for Bayesian modeling
and probabilistic programming in machine learning?
a. TensorFlow c. PyMC3
b. scikit-learn d. Matplotlib
147. Which Python library is commonly used for handling imbalanced
datasets in machine learning?
a. TensorFlow c. imbalanced-learn
b. scikit-learn d. Matplotlib
148. Which Python library provides support for graph computations
and deep learning on computational graphs?
a. TensorFlow c. PyTorch
b. scikit-learn d. NetworkX
149. Which Python library is commonly used for recommendation
systems and collaborative filtering in machine learning?
a. TensorFlow c. Surprise
b. scikit-learn d. Matplotlib
150. Which Python library provides support for dimensionality
reduction techniques such as Principal Component Analysis
(PCA)?
a. TensorFlow c. PyTorch
b. scikit-learn d. Theano
151. Which Python library is commonly used for data preprocessing
and feature scaling in machine learning?
a. NumPy c. Pandas
b. scikit-learn d. Matplotlib
152. Which Python library provides support for time series forecasting
using recurrent neural networks?
a. TensorFlow c. Keras
b. scikit-learn d. Matplotlib
153. Which Python library is commonly used for natural language
processing and named entity recognition tasks?
a. TensorFlow c. NLTK
b. scikit-learn d. Spacy
154. Which Python library provides support for anomaly detection and
outlier detection using machine learning algorithms?
a. TensorFlow c. PyTorch
b. scikit-learn d. PyOD
155. Which Python library is commonly used for data visualization and
creating static plots in machine learning?
a. NumPy c. Pandas
b. Keras d. Matplotlib
156. Which Python library provides support for natural language
processing and sentiment analysis using deep learning models?
a. TensorFlow c. NLTK
b. scikit-learn d. transformers
157. Which Python library is commonly used for time series forecasting
and analysis using statistical models and techniques?
a. Prophet c. Pandas
b. TensorFlow d. statsmodels
158. Which Python library provides support for pre-trained models
and transfer learning in machine learning?
a. TensorFlow
b. scikit-learn
c. PyTorch
d. Hugging Face Transformers
159. Which Python library is commonly used for text preprocessing
and feature extraction for natural language processing tasks?
a. TensorFlow c. NLTK
b. scikit-learn d. spaCy
160. Which library in Python is commonly used for implementing
linear regression?
a. NumPy c. scikit-learn
b. Pandas d. Matplotlib
161. What is the objective of linear regression?
a. Minimize the sum of squared errors
b. Maximize the accuracy of predictions
c. Reduce the number of features
d. None of the above
162. Which method in scikit-learn is used to fit a linear regression
model?
a. fit() c. transform()
b. predict() d. score()
163. In linear regression, what is the term used to represent the
coefficient of determination?
a. R-squared
b. Adjusted R-squared
c. Beta coefficient
d. Correlation coefficient
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
165. Which Python method is used to retrieve the coefficients of a
linear regression model in scikit-learn?
a. coef_ c. get_params()
b. coefficients() d. params_
166. Which metric is commonly used to evaluate the performance of a
linear regression model?
a. Accuracy
b. Precision
c. Mean Squared Error (MSE)
d. F1-score
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
169. Which method in scikit-learn is used to make predictions using a
trained linear regression model?
a. fit() c. predict()
b. transform() d. score()
170. In linear regression, what does the term residuals refer to?
a. The difference between predicted and actual values
b. Coefficients of the regression equation
c. The intercept of the regression line
d. The standard deviation of the dataset
171. Which Python library is commonly used to assess multi-
collinearity in linear regression?
a. NumPy c. Statsmodels
b. Pandas d. seaborn
172. In a multiple linear regression scenario, what does the Variance
Inflation Factor (VIF) measure?
a. The strength of association between each independent variable
and the dependent variable
b. The impact of outliers on the regression line
c. The extent of multi-collinearity among the independent variables
d. The predictive power of the regression model
173. Which statistical test helps in determining the statistical
significance of coefficients in linear regression?
a. T-test c. Chi-square test
b. ANOVA d. F-test
174. How is regularization helpful in linear regression?
a. It reduces bias in the model
b. It increases the number of features
c. It exacerbates overfitting
d. It increases variance in the model
175. Which method in scikit-learn is used to implement Ridge
regression?
a. Ridge()
b. LinearRegression()
c. Lasso()
d. fit()
176. Which technique can be used to handle overfitting in linear
regression by penalizing large coefficients?
a. L1 Regularization (Lasso)
b. L2 Regularization (Ridge)
c. Elastic Net
d. Both a and b
177. What is the purpose of feature scaling in linear regression?
a. To standardize the range of independent variables
b. To increase the number of features
c. To remove outliers from the dataset
d. To decrease the computational complexity
178. Which method is used to assess the goodness of fit in linear
regression by penalizing models with more variables?
a. AIC (Akaike Information Criterion)
b. BIC (Bayesian Information Criterion)
c. RMSE (Root Mean Squared Error)
d. MSE (Mean Squared Error)
179. In linear regression, what does the term heteroscedasticity refer
to?
a. Non-linearity in the data
b. Unequal variance of residuals across different values of the
independent variable
c. Perfect multicollinearity among predictors
d. The presence of outliers in the dataset
180. Which Python library offers tools for implementing nonlinear
regression models?
a. scikit-learn c. Statsmodels
b. TensorFlow d. PyTorch
181. Which characteristic differentiates nonlinear regression from
linear regression?
a. The presence of a dependent variable
b. The presence of an intercept term
c. The functional form of the relationship between variables
d. The number of predictor variables
182. Which method is commonly used to fit a nonlinear regression
model in scikit-learn?
a. fit() c. transform()
b. predict() d. score()
183. In nonlinear regression, what is the primary goal?
a. Minimize the sum of squared errors
b. Maximize the coefficient of determination
c. Reduce the number of features
d. None of the above
184. Which Python library is specifically designed for deep learning
and can handle complex nonlinear relationships?
a. Keras c. Statsmodels
b. scikit-learn d. TensorFlow
185. Which method in scikit-learn is used to make predictions using a
trained nonlinear regression model?
a. fit() c. predict()
b. transform() d. score()
186. Which technique is often used to improve the fit of a nonlinear
regression model by transforming the predictors or dependent
variable?
a. Regularization
b. Feature scaling
c. Polynomial regression
d. Data normalization
187. Which function in scikit-learn allows the implementation of a
Gaussian Process Regression (GPR) for nonlinear regression?
a. GaussianProcess()
b. DecisionTreeRegressor()
c. SVR()
d. MLPRegressor()
188. Which statistical measure is used to evaluate the goodness of fit in
nonlinear regression?
a. R-squared
b. Adjusted R-squared
c. F-statistic
d. Mean Squared Error (MSE)
189. What is the term used to describe a nonlinear regression model
that can be transformed into a linear model by mathematical
manipulation?
a. Polynomial regression
b. Exponential regression
c. Logarithmic regression
d. Linearizable regression
190. Which method in scikit-learn is commonly used for implementing
Support Vector Regression (SVR) for nonlinear regression tasks?
a. SVR()
b. LinearRegression()
c. RandomForestRegressor()
d. DecisionTreeRegressor()
191. Which technique is used to prevent overfitting in nonlinear
regression models by penalizing complex models?
a. Feature scaling
b. Regularization
c. Data transformation
d. Dimensionality reduction
192. Which type of nonlinear regression model represents an
exponential relationship between variables?
a. Power law model
b. Exponential model
c. Logarithmic model
d. Sigmoidal model
193. Which method in scikit-learn allows the implementation of
Decision Tree Regression for nonlinear regression?
a. DecisionTreeRegressor()
b. SVR()
c. MLPRegressor()
d. RandomForestRegressor()
194. What is the primary difference between linear regression and
nonlinear regression?
a. Linear regression assumes a linear relationship, while nonlinear
regression allows any functional relationship.
b. Linear regression uses more computational resources than
nonlinear regression.
c. Linear regression requires feature scaling, while nonlinear
regression does not.
d. Linear regression always has a higher accuracy than nonlinear
regression.
195. Which technique is used in scikit-learn to handle nonlinear
regression problems involving large datasets by splitting data into
subsets?
a. Bagging
b. Boosting
c. Random Forests
d. Gradient boosting
196. Which method in scikit-learn is commonly used to implement
Random Forest Regression for nonlinear regression problems?
a. DecisionTreeRegressor()
b. SVR()
c. RandomForestRegressor()
d. MLPRegressor()
197. Which type of nonlinear regression model uses a mathematical
function to fit a curve that approaches a horizontal asymptote?
a. Exponential model
b. Sigmoidal model
c. Polynomial model
d. Power law model
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
199. Which technique in nonlinear regression helps in handling multi-
collinearity among predictors?
a. Feature scaling
b. Regularization
c. Principal Component Analysis (PCA)
d. Polynomial transformation
200. Which Python library provides an implementation of the K-
Nearest Neighbors algorithm?
a. NumPy c. TensorFlow
b. scikit-learn d. Pandas
201. What type of learning does the K-Nearest Neighbors algorithm
belong to?
a. Unsupervised learning
b. Supervised learning
c. Semi-supervised learning
d. Reinforcement learning
202. In KNN, what does K represent?
a. Number of clusters
b. Number of features
c. Number of nearest neighbors
d. Number of iterations
203. Which method in scikit-learn is used to fit a KNN model?
a. fit() c. transform()
b. predict() d. score()
204. What is the key assumption behind the K-Nearest Neighbors
algorithm?
a. The data is linearly separable
b. The data is normally distributed
c. Similar data points tend to have similar output values
d. The data is balanced
205. Which metric is commonly used to measure the distance between
data points in KNN?
a. Euclidean distance
b. Manhattan distance
c. Minkowski distance
d. All of the above
206. What happens in tie-breaking when determining the class in KNN
with an even value of K?
a. Random selection
b. Select the first class encountered
c. Select the class with the lowest index
d. None of the above
207. Which parameter in the KNN algorithm specifies the weight
assigned to neighboring points for prediction?
a. n_neighbors
b. weights
c. algorithm
d. metric
208. What is the main disadvantage of the K-Nearest Neighbors
algorithm?
a. It requires a lot of memory
b. It is sensitive to outliers
c. It only works with numerical data
d. It is computationally expensive during training
209. Which method in scikit-learn is used to make predictions using a
trained KNN model?
a. fit() c. predict()
b. transform() d. score()
210. What happens to the performance of KNN as the value of K
increases?
a. It becomes more sensitive to outliers
b. It becomes less sensitive to noise
c. It tends to overfit the data
d. It tends to underfit the data
211. Which parameter in the KNN algorithm specifies the number of
neighbors to consider for classification or regression?
a. n_neighbors c. algorithm
b. weights d. metric
212. Which distance metric is suitable for categorical variables in
KNN?
a. Euclidean distance
b. Manhattan distance
c. Hamming distance
d. Cosine similarity
213. Which value of K in KNN might lead to overfitting the model to
the training data?
a. A very small value of K
b. A very large value of K
c. An odd value of K
d. K = 1
214. What does scaling the data accomplish in KNN?
a. Reduces computational time
b. Improves model performance
c. Makes the algorithm immune to outliers
d. None of the above
215. Which method in scikit-learn is used to find the distance between
two points?
a. distance()
b. euclidean_distance()
c. pairwise_distances()
d. calculate_distance()
216. How does the choice of K affect the bias-variance tradeoff in
KNN?
a. Higher K increases bias and decreases variance
b. Lower K increases bias and decreases variance
c. Higher K increases both bias and variance
d. Lower K increases both bias and variance
217. Which method in scikit-learn is used to evaluate the accuracy of a
KNN model?
a. evaluate()
b. accuracy_score()
c. score()
d. predict()
218. Which parameter in the KNN algorithm specifies the strategy used
to compute the nearest neighbors?
a. n_neighbors c. algorithm
b. weights d. metric
219. Which approach can be used to handle missing values in the KNN
algorithm?
a. Imputation
b. Deletion
c. Ignoring missing values
d. All of the above
220. Which Python library offers an implementation of decision tree
algorithms?
a. NumPy c. scikit-learn
b. TensorFlow d. Pandas
221. What type of learning does a decision tree algorithm belong to?
a. Unsupervised learning
b. Reinforcement learning
c. Supervised learning
d. Semi-supervised learning
222. What is the primary objective of a decision tree algorithm?
a. Maximize information gain
b. Minimize the number of nodes
c. Reduce feature complexity
d. None of the above
223. Which method in scikit-learn is used to fit a Decision Tree model?
a. fit() c. transform()
b. predict() d. score()
224. What is the criterion used to split nodes in a decision tree?
a. Gini impurity c. Entropy
b. Information gain d. All of the above
225. Which parameter in the decision tree algorithm specifies the
maximum depth of the tree?
a. max_depth
b. min_samples_split
c. criterion
d. splitter
226. In a decision tree, what does a leaf node represent?
a. A decision rule
b. A feature
c. A class label or output value
d. A splitting criterion
227. Which method in scikit-learn is used to make predictions using a
trained decision tree model?
a. fit() c. predict()
b. transform() d. score()
228. What is pruning in the context of decision trees?
a. Adding more nodes to the tree
b. Removing nodes to reduce complexity and overfitting
c. Reducing the depth of the tree
d. None of the above
229. Which technique is used to handle missing values in a decision
tree?
a. Deleting the rows with missing values
b. Assigning the most frequent value of the feature
c. Assigning a random value to the missing data
d. None of the above
230. What happens to the bias-variance tradeoff as the depth of a
decision tree increases?
a. Bias increases and variance decreases
b. Bias decreases and variance increases
c. Both bias and variance increase
d. Both bias and variance decrease
231. Which parameter in a decision tree algorithm specifies the
minimum number of samples required to split an internal node?
a. max_depth
b. min_samples_split
c. criterion
d. splitter
232. Which method in scikit-learn allows the visualization of a decision
tree?
a. plot() c. plot_tree()
b. visualize() d. show()
233. In a decision tree, what is entropy used for?
a. To measure the impurity of a node
b. To calculate information gain
c. To define the splitting criteria
d. All of the above
234. Which technique can be used to prevent overfitting in a decision
tree?
a. Increasing the maximum depth
b. Reducing the maximum depth
c. Adding more features
d. None of the above
235. Which method in scikit-learn is used to evaluate the importance of
features in a decision tree model?
a. feature_importances_()
b. evaluate_features()
c. importance_score()
d. feature_score()
236. Which measure is used by decision trees to determine the best
split?
a. Gini impurity
b. Information gain
c. Entropy
d. All of the above
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
238. Which parameter in a decision tree algorithm specifies the
strategy used to select the feature at each node?
a. max_depth
b. min_samples_split
c. criterion
d. splitter
239. Which method in scikit-learn is used to evaluate the accuracy of a
decision tree model?
a. evaluate() c. score()
b. accuracy_score() d. predict()
240. Which Python library offers an implementation of logistic
regression?
a. NumPy c. scikit-learn
b. TensorFlow d. Pandas
241. What type of learning does logistic regression belong to?
a. Unsupervised learning
b. Supervised learning
c. Reinforcement learning
d. Semi-supervised learning
242. In logistic regression, what type of problem does it solve?
a. Regression problem
b. Classification problem
c. Clustering problem
d. Dimensionality reduction problem
243. Which method in scikit-learn is used to fit a logistic regression
model?
a. fit() c. transform()
b. predict() d. score()
244. What is the logistic function used for in logistic regression?
a. To calculate the mean squared error
b. To convert linear output into probabilities
c. To compute the accuracy of the model
d. None of the above
245. Which metric is commonly used to evaluate the performance of a
logistic regression model?
a. R-squared
b. Accuracy
c. Mean Squared Error (MSE)
d. F1-score
246. What does the sigmoid function do in logistic regression?
a. Normalizes the data
b. Maps any real-valued number into the range [0, 1]
c. Reduces the dimensionality of the data
d. Calculates the residuals
247. Which method in scikit-learn is used to make predictions using a
trained logistic regression model?
a. fit() c. predict()
b. transform() d. score()
248. In logistic regression, what is the cost function used for model
optimization?
a. Mean Squared Error (MSE)
b. Cross-Entropy Loss
c. R-squared
d. Absolute Error
249. Which parameter in logistic regression penalizes large coefficients
to prevent overfitting?
a. C c. solver
b. penalty d. max_iter
250. Which method in scikit-learn allows setting the regularization
strength in logistic regression?
a. set_penalty()
b. set_C()
c. set_regularization()
d. set_strength()
251. What does the term logit represent in logistic regression?
a. Probability of the positive class
b. The linear combination of features and coefficients
c. The probability of the negative class
d. None of the above
252. Which parameter in logistic regression determines the solver
algorithm to use in optimization?
a. C c. solver
b. penalty d. max_iter
253. How does logistic regression handle multi-collinearity among
predictor variables?
a. By removing redundant features automatically
b. By assigning higher weights to correlated features
c. By ignoring correlated features during training
d. None of the above
254. Which method in scikit-learn is used to evaluate the accuracy of a
logistic regression model?
a. evaluate() c. score()
b. accuracy_score() d. predict()
255. What does the term odds ratio signify in logistic regression?
a. The probability of an event occurring
b. The ratio of the probability of success to the probability of failure
c. The difference between predicted and actual values
d. None of the above
256. Which parameter in logistic regression determines the maximum
number of iterations for optimization?
a. C c. solver
b. penalty d. max_iter
257. Which method in scikit-learn allows accessing the coefficients of a
logistic regression model?
a. get_coefficients()
b. coef_()
c. retrieve_parameters()
d. weights_()
258. What is the primary difference between linear regression and
logistic regression?
a. Linear regression predicts continuous values, while logistic
regression predicts probabilities.
b. Logistic regression uses more computational resources than linear
regression.
c. Linear regression is more suitable for classification tasks.
d. Logistic regression requires feature scaling, while linear
regression does not.
259. Which method in scikit-learn is used to find the probability
estimates for the classes in logistic regression?
a. predict_proba()
b. probability_estimate()
c. class_probabilities()
d. probability_score()
260. Which Python library offers an implementation of Support Vector
Machines?
a. NumPy c. scikit-learn
b. TensorFlow d. Pandas
261. What type of learning does Support Vector Machines belong to?
a. Unsupervised learning
b. Supervised learning
c. Reinforcement learning
d. Semi-supervised learning
262. In SVM, what is a hyperplane?
a. A line that separates classes with the maximum margin
b. A line connecting support vectors
c. A line that minimizes classification error
d. None of the above
263. Which method in scikit-learn is used to fit an SVM model?
a. fit()
b. predict()
c. transform()
d. score()
264. What is the purpose of kernels in SVM?
a. To project data into higher-dimensional space
b. To decrease the margin between classes
c. To reduce computational complexity
d. None of the above
265. Which kernel in SVM is suitable for linearly separable data?
a. Linear kernel
b. Polynomial kernel
c. Radial Basis Function (RBF) kernel
d. Sigmoid kernel
266. Which parameter in SVM controls the tradeoff between
maximizing the margin and minimizing the classification error?
a. gamma c. kernel
b. C d. degree
267. Which method in scikit-learn is used to make predictions using a
trained SVM model?
a. fit() c. predict()
b. transform() d. score()
268. What is the role of support vectors in SVM?
a. They are the data points closest to the decision boundary
b. They define the weight vector in SVM
c. They are outliers that are not considered in training
d. None of the above
269. Which kernel in SVM allows non-linear decision boundaries?
a. Linear kernel
b. Polynomial kernel
c. Radial Basis Function (RBF) kernel
d. Sigmoid kernel
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
271. Which parameter in SVM influences the smoothness of the
decision boundary?
a. gamma c. kernel
b. C d. degree
272. How does increasing the value of C affect the SVM model?
a. It increases the regularization strength
b. It increases the margin width
c. It decreases the margin width
d. None of the above
273. Which kernel in SVM is analogous to a neural network with a
sigmoid activation function?
a. Linear kernel
b. Polynomial kernel
c. Radial Basis Function (RBF) kernel
d. Sigmoid kernel
274. Which method in scikit-learn is used to set the kernel type in
SVM?
a. set_kernel() c. set_params()
b. kernel_type() d. set_kernel_type()
275. How does SVM handle multi-class classification problems?
a. It uses One-vs-One strategy
b. It uses One-vs-Rest strategy
c. It cannot handle multi-class problems
d. None of the above
276. Which parameter in SVM determines the degree of the polynomial
kernel?
a. gamma c. kernel
b. C d. degree
277. Which method in scikit-learn is used to retrieve the support
vectors from a trained SVM model?
a. get_support_vectors()
b. support_vectors_()
c. retrieve_support_vectors()
d. svm_vectors_()
278. What happens to the bias-variance tradeoff in SVM as ‘C’
increases?
a. Bias increases and variance decreases
b. Bias decreases and variance increases
c. Both bias and variance increase
d. Both bias and variance decrease
279. Which method in scikit-learn is used to evaluate the accuracy of
an SVM model?
a. evaluate() c. score()
b. accuracy_score() d. predict()
280. Which Python library offers tools for model evaluation and
metrics computation?
a. NumPy c. scikit-learn
b. TensorFlow d. Pandas
281. Which metric is commonly used to evaluate classification models
when classes are imbalanced?
a. Accuracy c. Recall
b. Precision d. F1-score
282. What is the purpose of a confusion matrix in model evaluation?
a. To measure the computational complexity of the model
b. To visualize the performance of a classification model
c. To evaluate the model’s predictive power
d. None of the above
283. Which method in scikit-learn is used to generate a confusion
matrix for a classification model?
a. confusion_matrix()
b. generate_confusion_matrix()
c. evaluate_confusion()
d. matrix_evaluation()
284. Which evaluation metric is more suitable for imbalanced datasets
when the focus is on minimizing false negatives?
a. Accuracy
b. Precision
c. Recall
d. F1-score
285. Which method in scikit-learn is used to compute the area under
the ROC curve (AUC-ROC) for binary classification?
a. compute_auc() c. auc()
b. roc_curve() d. roc_auc_score()
286. In K-fold cross-validation, what does ‘K’ represent?
a. The number of classes in the dataset
b. The number of times the dataset is shuffled
c. The number of models trained
d. The number of folds or subsets into which the data is divided
287. Which method in scikit-learn is used to perform K-fold cross-
validation?
a. kfold_validate()
b. cross_validate()
c. perform_cross_validation()
d. validate()
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
289. What does the R-squared value represent in regression
evaluation?
a. The proportion of variance explained by the model
b. The residual error of the model
c. The mean absolute error of predictions
d. None of the above
290. Which method in scikit-learn is used to compute R-squared for
regression models?
a. evaluate_r_squared()
b. r_squared_score()
c. score()
d. compute_r_squared()
291. What does the term overfitting refer to in model evaluation?
a. The model performs well on the training data but poorly on
unseen data
b. The model performs equally well on training and test data
c. The model is too simple and cannot capture the complexity of the
data
d. None of the above
292. Which evaluation metric penalizes large errors more severely in
regression models?
a. Mean Absolute Error (MAE)
b. Root Mean Squared Error (RMSE)
c. Mean Squared Error (MSE)
d. R-squared
293. What is the purpose of the train-test split method in model
evaluation?
a. To train the model on the entire dataset
b. To create a validation set for hyperparameter tuning
c. To ensure the model is overfitting the data
d. To evaluate the model’s performance on unseen data
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()
295. What does the term underfitting refer to in model evaluation?
a. The model is too complex and fits the noise in the data
b. The model performs well on unseen data
c. The model is too simple to capture the underlying patterns in the
data
d. None of the above
296. Which metric is used to measure the similarity between predicted
and actual values in regression models?
a. R-squared
b. Mean Squared Error (MSE)
c. F1-score
d. None of the above
297. What does cross-entropy represent in classification model
evaluation?
a. The proportion of correctly classified instances
b. The average log loss between predicted and actual probabilities
c. The accuracy of the model
d. None of the above
298. Which method in scikit-learn is used to compute cross-entropy for
classification models?
a. evaluate_cross_entropy()
b. cross_entropy_score()
c. log_loss()
d. compute_cross_entropy()
299. Which evaluation method is used to mitigate data leakage in model
assessment?
a. Holdout validation
b. K-fold cross-validation
c. Leave-One-Out cross-validation
d. None of the above
300. Which evaluation metric is sensitive to class imbalance and is
calculated as the harmonic mean of precision and recall?
a. Accuracy c. Recall
b. Precision d. F1-score
301. Which Python library is used for creating 2D graphics and
visualizations, including plots, charts, and histograms?
a. Pandas c. NumPy
b. Matplotlib d. Seaborn
302. Which module within Matplotlib is primarily used for creating
plots and figures?
a. matplotlib.pyplot
b. matplotlib.figure
c. matplotlib.plot
d. matplotlib.graph
303. What function in Matplotlib is used to create a line plot?
a. plt.plot() c. plt.draw()
b. plt.line() d. plt.create()
304. Which method in Matplotlib is used to set the title of a plot?
a. plt.set_title()
b. plt.title()
c. plt.plot_title()
d. plt.set_plot_title()
305. What Matplotlib function is used to create a scatter plot?
a. plt.scatter()
b. plt.plot()
c. plt.draw()
d. plt.create_scatter()
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()
307. What function is used in Matplotlib to display the plot?
a. plt.show() c. plt.plot()
b. plt.display() d. plt.view()
308. Which Matplotlib method is used to create a histogram?
a. plt.hist()
b. plt.plot()
c. plt.bar()
d. plt.create_histogram()
309. What command in Matplotlib sets the figure size of a plot?
a. plt.figure_size()
b. plt.set_figure_size()
c. plt.figsize()
d. plt.set_size()
310. Which Matplotlib method is used to add a legend to a plot?
a. plt.add_legend()
b. plt.legend()
c. plt.create_legend()
d. plt.set_legend()
311. Which Python library is primarily used for natural language
processing tasks, such as tokenization, stemming, and part-of-
speech tagging?
a. NumPy c. NLTK
b. Pandas d. Scikit-learn
312. Which NLTK function is used to tokenize a text into words or
sentences?
a. nltk.tokenize()
b. nltk.split()
c. nltk.word_tokenize()
d. nltk.text_tokenize()
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()
315. What NLTK function is used to perform part-of-speech tagging on
words in a sentence?
a. nltk.pos_tag() c. nltk.tag_pos()
b. nltk.tag() d. nltk.postag()
316. Which NLTK module provides access to various corpora and
lexical resources?
a. nltk.corpus c. nltk.data
b. nltk.resources d. nltk.lexicon
317. What NLTK tool can be used to visualize text data through
dispersion plots and frequency distributions?
a. nltk.plot() c. nltk.draw()
b. nltk.visualize() d. nltk.Text()
318. Which NLTK method is used for lemmatization, reducing words
to their base or dictionary form?
a. nltk.lemmatizer()
b. nltk.lemmatize()
c. nltk.lemma()
d. nltk.lemmatization()
319. What NLTK package provides tools for creating and training
natural language processing models?
a. nltk.ml c. nltk.learn
b. nltk.models d. nltk.classify
320. Which NLTK method is used to compute the similarity between
two texts or documents?
a. nltk.similarity()
b. nltk.compute_similarity()
c. nltk.text_similarity()
d. nltk.Text().similarity()
321. Which command installs NLTK using pip in a Mac/Unix
environment?
a. pip install nltk c. brew install nltk
b. sudo install nltk d. conda install nltk
322. What command is used to open the Python shell in the terminal on
Mac/Unix?
a. python-shell c. open-python
b. python d. start-python
323. Which Python package manager is commonly used for installing
NLTK on Mac/Unix?
a. pip c. brew
d. apt b. conda
324. Which command installs NLTK along with additional data
packages using pip in a Mac/Unix environment?
a. pip install nltk
b. pip install nltk-data
c. pip install nltk --additional-data
d. pip install nltk && nltk.download()
325. What utility allows installing NLTK using Homebrew on
Mac/Unix systems?
a. brew install nltk
b. pip install nltk
c. conda install nltk
d. apt-get install nltk
326. Which step follows the installation of NLTK via pip on a
Mac/Unix system?
a. Import NLTK in Python script directly
b. Set NLTK environment variables
c. Download NLTK data
d. Restart the terminal
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
328. What command checks the installed version of NLTK on a
Mac/Unix system?
a. pip version nltk c. pip show nltk
b. nltk --version d. nltk version
329. What does the NLTK download() function facilitate after
installation on Mac/Unix systems?
a. Installs NLTK dependencies
b. Downloads additional NLTK data and resources
c. Upgrades NLTK to the latest version
d. Sets up NLTK configuration
330. Which directory stores NLTK data after downloading on a
Mac/Unix system?
a. /usr/share/nltk_data
b. ~/nltk_data
c. /usr/local/nltk_data
d. /var/lib/nltk_data
331. Which command is used to install NLTK using pip in a Windows
environment?
a. pip install nltk
b. pip3 install nltk
c. conda install nltk
d. download nltk
332. What Python package manager is commonly used for installing
NLTK on Windows?
a. pip c. npm
b. conda d. chocolatey
333. Which command installs NLTK along with additional data
packages using pip in a Windows environment?
a. pip install nltk-data
b. pip install nltk --all-data
c. pip install nltk && nltk.download()
d. pip install nltk && download-nltk-data
334. What is the recommended way to start the NLTK downloader
after installation on Windows?
a. Run the nltk.download() function in a Python script
b. Use the command prompt and type nltk.download()
c. Click on the NLTK Downloader shortcut in the Start menu
d. Open a web browser and visit the NLTK download page
335. Which utility can be used to install NLTK on Windows in an
automated fashion and manage Python packages?
a. PowerShell
b. Command Prompt
c. Anaconda Prompt
d. Chocolatey
336. What does the NLTK download() function facilitate after
installation on Windows?
a. Installs NLTK dependencies
b. Downloads NLTK source code
c. Downloads additional NLTK data and resources
d. Sets up NLTK configuration
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
338. Where does NLTK store downloaded data on a Windows system
by default?
a. C:\nltk_data
b. /usr/share/nltk_data
c. C:\Users<username>\AppData\Roaming\nltk_data
d. C:\Program Files\nltk
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
341. What algorithmic approach can handle categorical variables
effectively in a machine learning model?
a. One-Hot Encoding
b. Ordinal Encoding
c. Label Encoding
d. Frequency Encoding
342. Which evaluation metric is suitable for imbalanced datasets and
gives more weight to false positives than false negatives?
a. Accuracy c. Recall
b. Precision d. F1-score
343. In ensemble methods like Random Forests, what does
bootstrapping involve?
a. Aggregating multiple models’ predictions
b. Using multiple decision trees with different depths
c. Creating multiple datasets through resampling with replacement
d. Sampling the entire dataset without replacement
344. What is the purpose of regularization in machine learning models?
a. To increase the complexity of the model
b. To reduce the risk of overfitting
c. To decrease the learning rate
d. To minimize the bias in the model
345. What does the term hyperparameters refer to in machine learning
algorithms?
a. Model parameters learned during training
b. Parameters adjusted to optimize model performance
c. Input features used for prediction
d. Loss function parameters
346. In gradient boosting algorithms like XGBoost, what is the purpose
of the learning rate parameter?
a. It controls the number of trees in the ensemble
b. It determines the depth of individual trees
c. It regulates the contribution of each tree to the ensemble
d. It minimizes the feature space
347. Which method is commonly used to handle missing data before
training a machine learning model?
a. Mean imputation
b. Mode imputation
c. Median imputation
d. Random imputation
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
349. In a neural network, what does the activation function in a hidden
layer determine?
a. The learning rate of the network
b. The output of the hidden layer
c. The loss function for optimization
d. The number of neurons in the layer
350. What problem does the application of the K-nearest neighbors
algorithm face when dealing with high-dimensional data?
a. Overfitting
b. Curse of dimensionality
c. Underfitting
d. Feature redundancy
Conclusion
This chapter aimed to serve as a gateway, inviting readers into the dynamic
world of algorithms, predictive models, and data-driven decision-making. By
engaging with these thought-provoking multiple-choice questions, learners
have embarked on a journey that unravels the complexities of machine
learning while harnessing the power of Python’s libraries and methodologies.
With this foundational knowledge, readers are better equipped to explore,
innovate, and apply machine learning principles to solve real-world
challenges. This chapter is but a stepping stone, inspiring continual learning
and exploration in the endlessly evolving realm of machine learning with
Python. The forthcoming chapter will discuss MCQs related to clustering in
Python.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 a 51 d 101 a 151 b 201 b
2 d 52 b 102 b 152 c 202 c
3 a 53 a 103 c 153 c 203 a
4 a 54 c 104 c 154 d 204 c
5 b 55 a 105 c 155 d 205 d
6 d 56 b 106 b 156 d 206 a
7 a 57 c 107 c 157 d 207 b
8 a 58 a 108 b 158 d 208 d
9 a 59 a 109 c 159 d 209 c
10 c 60 a 110 b 160 c 210 d
11 a 61 b 111 b 161 a 211 a
12 b 62 b 112 c 162 a 212 c
13 a 63 b 113 a 163 a 213 d
14 d 64 d 114 b 164 c 214 b
15 a 65 b 115 d 165 a 215 c
16 d 66 b 116 c 166 c 216 a
17 c 67 c 117 c 167 c 217 b
18 a 68 b 118 a 168 a 218 c
19 c 69 b 119 a 169 c 219 a
20 a 70 c 120 c 170 a 220 c
21 a 71 b 121 d 171 c 221 c
22 b 72 c 122 d 172 c 222 a
23 a 73 a 123 d 173 a 223 a
24 d 74 b 124 b 174 a 224 d
25 c 75 b 125 b 175 a 225 a
26 a 76 c 126 a 176 d 226 c
27 c 77 c 127 d 177 a 227 c
28 c 78 c 128 b 178 b 228 b
29 b 79 b 129 c 179 b 229 b
30 b 80 c 130 b 180 a 230 c
31 d 81 b 131 a 181 c 231 b
32 b 82 b 132 a 182 a 232 c
33 a 83 c 133 d 183 a 233 d
34 b 84 c 134 c 184 d 234 b
35 b 85 b 135 d 185 c 235 a
36 a 86 c 136 c 186 c 236 d
37 c 87 b 137 a 187 a 237 a
38 a 88 b 138 d 188 d 238 d
39 c 89 c 139 c 189 d 239 c
40 a 90 c 140 a 190 a 240 c
41 b 91 b 141 d 191 b 241 b
42 a 92 b 142 d 192 b 242 b
43 c 93 b 143 d 193 a 243 a
44 b 94 c 144 c 194 a 244 b
45 b 95 c 145 d 195 a 245 b
46 d 96 b 146 c 196 c 246 b
47 c 97 c 147 c 197 b 247 c
48 a 98 b 148 d 198 d 248 b
49 a 99 c 149 c 199 c 249 b
50 a 100 b 150 b 200 b 250 b
CHAPTER 17
Clustering with Python
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.
Multiple choice questions
1. What is unsupervised learning?
a. A type of machine learning algorithm that is used to classify data
b. A type of machine learning algorithm that uses labeled data to
make predictions
c. A type of machine learning algorithm that does not require
labeled data
d. A type of machine learning algorithm that focuses on regression
analysis
2. Which of the following is a common application of unsupervised
learning?
a. Image classification
b. Fraud detection
c. Speech recognition
d. Sentiment analysis
3. What is clustering in unsupervised learning?
a. A technique used to group similar data points together
b. A technique used to classify data into discrete categories
c. A technique used to identify outliers in a dataset
d. A technique used to predict continuous values
4. Which algorithm is commonly used for clustering in unsupervised
learning?
a. K-means
b. Decision tree
c. Naive Bayes
d. Support vector machine
5. What is dimensionality reduction in unsupervised learning?
a. A technique used to increase the number of features in a dataset
b. A technique used to reduce noise in a dataset
c. A technique used to reduce the number of features in a dataset
d. A technique used to decrease computational complexity
6. Which algorithm is commonly used for dimensionality reduction
in unsupervised learning?
a. Decision tree
b. Random forest
c. Principal Component Analysis (PCA)
d. Linear regression
7. What is anomaly detection in unsupervised learning?
a. A technique used to identify outliers in a dataset
b. A technique used to evaluate classification accuracy
c. A technique used to evaluate regression accuracy
d. A technique used to handle missing or incomplete data
8. Which algorithm is commonly used for anomaly detection in
unsupervised learning?
a. K-means
b. Support vector machine
c. Decision tree
d. Isolation Forest
9. What is the goal of unsupervised learning?
a. To minimize the prediction error
b. To maximize the accuracy of predictions
c. To discover hidden patterns or structures in data
d. To optimize a cost function
10. Which of the following is not an advantage of unsupervised
learning?
a. It can uncover hidden patterns in data
b. It can handle unlabeled data
c. It can improve the accuracy of predictions
d. It can be used for exploratory data analysis
11. What is the main challenge of unsupervised learning?
a. Lack of labeled data for training
b. Limited computational resources
c. Difficulties in handling missing or incomplete data
d. Complex feature engineering process
12. What is the key difference between supervised and unsupervised
learning?
a. Supervised learning requires labeled data, while unsupervised
learning does not
b. Supervised learning focuses on regression analysis, while
unsupervised learning focuses on classification
c. Supervised learning can handle missing or incomplete data, while
unsupervised learning cannot
d. Supervised learning requires feature engineering, while
unsupervised learning does not
13. Which of the following is an example of unsupervised learning
algorithm?
a. Naive Bayes
b. Linear regression
c. K-means clustering
d. Support vector machine
14. What is the output of unsupervised learning algorithms?
a. Labels
b. Predicted values
c. Clusters or groups
d. Confidence scores
15. Which technique is used to evaluate the performance of clustering
algorithms?
a. Accuracy
b. F1 score
c. Silhouette coefficient
d. Mean squared error
16. What is the curse of dimensionality in unsupervised learning?
a. The difficulty in handling missing or incomplete data
b. The increase in computational complexity with high-dimensional
data
c. The need for feature engineering
d. The limitation of certain algorithms to low-dimensional data
17. Which of the following is a distance metric commonly used in
clustering algorithms?
a. Euclidean distance
b. Bayesian distance
c. Manhattan distance
d. Cosine distance
18. Which unsupervised learning technique is used to impute missing
values in a dataset?
a. Principal Component Analysis (PCA)
b. K-means clustering
c. Decision tree
d. Expectation-Maximization (EM) algorithm
19. Which algorithm is commonly used for density estimation in
unsupervised learning?
a. Decision tree
b. Naive Bayes
c. Gaussian Mixture Models (GMM)
d. K-nearest neighbors
20. What is the main advantage of hierarchical clustering over K-
means clustering?
a. It is faster and more scalable
b. It does not require specifying the number of clusters
c. It can handle high-dimensional data
d. It guarantees convergence to the global optimum
21. Which algorithm is commonly used for anomaly detection in time
series data?
a. K-means
b. DBSCAN
c. Autoencoder
d. Support vector machine
22. Which unsupervised learning technique is used for sequential
pattern mining?
a. K-means clustering
b. Decision tree
c. Hidden Markov Models (HMM)
d. Random forest
23. Which technique is commonly used for feature extraction in
unsupervised learning?
a. K-means clustering
b. Linear regression
c. Principal Component Analysis (PCA)
d. Naive Bayes
24. Which algorithm is commonly used for topic modeling in natural
language processing?
a. Support vector machine
b. Decision tree
c. K-means clustering
d. Latent Dirichlet Allocation (LDA)
25. What is the main goal of outlier detection in unsupervised
learning?
a. To identify the most common data points
b. To identify the most important features
c. To identify data points that do not conform to the expected
patterns
d. To identify clusters or groups in the data
26. Which algorithm is commonly used for outlier detection in
unsupervised learning?
a. K-means
b. Isolation Forest
c. Linear regression
d. Naive Bayes
27. What is the main disadvantage of unsupervised learning?
a. It requires a large amount of labeled data for training
b. It can be computationally expensive for large datasets
c. It is limited to linear relationships in data
d. It is less accurate than supervised learning algorithms
28. Which unsupervised learning technique is used to recommend
items to users?
a. Apriori algorithm
b. Collaborative filtering
c. Principal Component Analysis (PCA)
d. Random forest
29. Which algorithm is commonly used for community detection in
network analysis?
a. Decision tree
b. K-means clustering
c. Louvain algorithm
d. Support vector machine
30. What is the main goal of feature selection in unsupervised
learning?
a. To increase the dimensionality of the data
b. To reduce the number of features in the data
c. To increase the amount of noise in the data
d. To improve the interpretability of the data
31. Which unsupervised learning technique is used for anomaly
detection in network traffic analysis?
a. DBSCAN clustering
b. K-means clustering
c. Isolation Forest
d. Linear regression
32. Which algorithm is commonly used for matrix factorization in
recommender systems?
a. Naive Bayes c. SVD
b. PCA d. Decision tree
33. What is the main challenge in handling missing or incomplete data
in unsupervised learning?
a. Determining the optimal imputation strategy
b. Dealing with outliers in the data
c. Choosing the right clustering algorithm
d. Identifying the appropriate feature transformation technique
34. Which unsupervised learning technique is used for pattern
recognition in images?
a. Linear regression
b. K-means clustering
c. Convolutional Neural Networks
d. Apriori algorithm
35. What is the main objective of self-organizing maps in
unsupervised learning?
a. To classify data points into discrete categories
b. To find associations between different data points
c. To visualize high-dimensional data in a lower dimensional space
d. To predict continuous values based on input features
36. Which algorithm is commonly used for density-based clustering in
unsupervised learning?
a. K-means c. DBSCAN
b. Decision tree d. Random forest
37. What is the main advantage of non-parametric approaches in
unsupervised learning?
a. They make strong assumptions about data distribution.
b. They can handle complex and non-linear relationships in data.
c. They require a large amount of labeled data for training.
d. They have lower computational complexity compared to
parametric approaches.
38. Which algorithm is commonly used for feature extraction in
computer vision applications?
a. Decision tree
b. Support vector machine
c. K-means clustering
d. CNN
39. What is the main purpose of data preprocessing in unsupervised
learning?
a. To increase the computational efficiency of algorithms
b. To remove outliers from the data
c. To normalize or scale the data
d. To increase the accuracy of predictions
40. Which unsupervised learning technique is commonly used for
exploratory data analysis?
a. Decision tree
b. K-means clustering
c. PCA
d. Random forest
41. What is the main objective of generative models in unsupervised
learning?
a. To classify data points into discrete categories
b. To generate new samples that resemble the training data
c. To identify clusters or groups in the data
d. To predict continuous values based on input features
42. Which algorithm is commonly used for matrix completion in
recommender systems?
a. Singular Value Decomposition (SVD)
b. Naive Bayes
c. K-means clustering
d. Random forest
43. What is the main advantage of semi-supervised learning over
unsupervised learning?
a. It can handle missing or incomplete data
b. It requires fewer labeled data for training
c. It can handle large and high-dimensional datasets
d. It guarantees convergence to the global optimum
44. Which unsupervised learning technique is used for association rule
mining in market basket analysis?
a. PCA
b. Apriori algorithm
c. Random forest
d. Support vector machine
45. What is the main objective of manifold learning in unsupervised
learning?
a. To identify clusters or groups in the data
b. To visualize high-dimensional data in a lower dimensional space
c. To classify data points into discrete categories
d. To predict continuous values based on input features
46. Which algorithm is commonly used for graph-based clustering in
unsupervised learning?
a. Decision tree
b. K-means clustering
c. Spectral clustering
d. Support vector machine
47. What is the main drawback of using unsupervised learning for
anomaly detection?
a. It cannot handle high-dimensional data
b. It requires a large amount of labeled data for training
c. It may produce false positives or false negatives
d. It has higher computational complexity compared to supervised
learning
48. Which unsupervised learning technique is used for predicting
missing values in a time series dataset?
a. Decision tree
b. K-means clustering
c. Seasonal Holt-Winters method
d. Support vector machine
49. What is the main advantage of ensemble methods in unsupervised
learning?
a. They can handle non-linear relationships in data
b. They require a large amount of labeled data for training
c. They are less prone to overfitting compared to single models
d. They have lower computational complexity compared to single
models
50. Which unsupervised learning technique is used for document
clustering in natural language processing?
a. Decision tree
b. K-means clustering
c. Latent Dirichlet Allocation (LDA)
d. Support vector machine
51. What is the main objective of generative adversarial networks
(GANs) in unsupervised learning?
a. To classify data points into discrete categories
b. To generate new samples that resemble the training data
c. To identify clusters or groups in the data
d. To predict continuous values based on input features
52. Which algorithm is commonly used for non-negative matrix
factorization in unsupervised learning?
a. Naive Bayes
b. Principal Component Analysis (PCA)
c. K-means clustering
d. Non-negative Matrix Factorization (NMF)
53. What is the main goal of unsupervised learning in
recommendation systems?
a. To increase the interpretability of the data
b. To classify data points into discrete categories
c. To generate personalized recommendations for users
d. To predict continuous values based on input features
54. Which unsupervised learning technique is used for image
segmentation?
a. Linear regression
b. K-means clustering
c. Convolutional Neural Networks (CNN)
d. Random forest
55. What is the main objective of word embeddings in natural
language processing?
a. To classify documents into discrete categories
b. To generate new sentences based on input keywords
c. To identify clusters or groups of words
d. To represent words as dense vectors in a high-dimensional space
56. Which algorithm is commonly used for density estimation in
unsupervised learning?
a. Decision tree
b. Naive Bayes
c. Gaussian Mixture Models (GMM)
d. K-nearest neighbors
57. What is the main objective of community detection in
unsupervised learning?
a. To classify data points into discrete categories
b. To generate personalized recommendations for users
c. To identify clusters or groups in a network
d. To predict continuous values based on input features
58. Which unsupervised learning technique is used for word sense
disambiguation in natural language processing?
a. Decision tree
b. K-means clustering
c. Latent Semantic Analysis (LSA)
d. Support vector machine
59. What is the main drawback of using unsupervised learning
algorithms for classification tasks?
a. They require a large amount of labeled data for training
b. They are prone to overfitting in high-dimensional spaces
c. They cannot handle non-linear relationships in data
d. They have higher computational complexity compared to
supervised learning
60. Which algorithm is commonly used for density-based anomaly
detection in unsupervised learning?
a. K-means
b. DBSCAN
c. Autoencoder
d. Support vector machine
61. What is the main objective of t-SNE in unsupervised learning?
a. To classify data points into discrete categories
b. To visualize high-dimensional data in a lower dimensional space
c. To identify clusters or groups in the data
d. To predict continuous values based on input features
62. Which unsupervised learning technique is used for concept drift
detection in data streams?
a. Decision tree
b. K-means clustering
c. Random forest
d. Online clustering algorithms
63. What is the main objective of k-medoids clustering in
unsupervised learning?
a. To classify data points into discrete categories
b. To generate personalized recommendations for users
c. To identify clusters or groups in the data
d. To predict continuous values based on input features
64. Which of the following clustering algorithms is not based on
distance?
a. K-means clustering
b. Hierarchical clustering
c. Density-Based Spatial Clustering of Applications with Noise
(DBSCAN)
d. Mean Shift
65. What is the objective of K-means clustering?
a. To minimize the within-cluster sum of squares
b. To maximize the between-cluster sum of squares
c. To maximize the silhouette coefficient
d. To minimize the number of clusters
66. Which initialization technique for K-means chooses random data
points as initial centroids?
a. K-means++
b. K-means#
c. Random initialization
d. Sklearn initialization
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
68. Which clustering algorithm can handle non-linearly separable
data?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. Mean Shift
d. Spectral clustering
69. What is the output of hierarchical clustering?
a. A dendrogram
b. A set of cluster centroids
c. A set of cluster labels
d. A set of prototypes
70. Which parameter in DBSCAN controls the maximum distance
between two samples for them to be considered as in the same
neighborhood?
a. Epsilon c. Metric
b. Min_samples d. Leaf_size
71. What distance metric is commonly used in K-means clustering?
a. Euclidean distance
b. Manhattan distance
c. Hamming distance
d. Minkowski distance
72. Which of the following clustering algorithms works by iteratively
reassigning each data point to the nearest cluster centroid?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
73. Which of the following statements about K-means clustering is
true?
a. It guarantees convergence to the global optimum
b. It is sensitive to the initial choice of centroids
c. It is not affected by outliers in the data
d. It works well with high-dimensional data
74. In hierarchical clustering, what is the linkage criterion used to
measure the dissimilarity between clusters?
a. Single-linkage
b. Complete-linkage
c. Average-linkage
d. Ward-linkage
75. What does the silhouette coefficient measure in clustering?
a. The compactness of each cluster
b. The separation between clusters
c. The quality of the cluster assignments
d. The computational complexity of the algorithm
76. Which clustering algorithm is sensitive to the order of the data
points?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. DBSCAN
d. Mean Shift
77. What is the advantage of spectral clustering over K-means
clustering for clustering high-dimensional data?
a. It is more computationally efficient
b. It can handle non-linearly separable data
c. It does not require specifying the number of clusters beforehand
d. It can capture complex patterns without relying on distances
78. What is the limitation of K-means clustering for handling
categorical data?
a. It cannot handle missing values
b. It assumes numerical distances between data points
c. It cannot handle non-linearly separable data
d. It requires the number of clusters to be specified beforehand
79. Which Python library provides the implementation of K-means
clustering?
a. PyTorch
b. Keras
c. Scikit-learn
d. TensorFlow
80. What is the purpose of scaling the data before performing K-
means clustering?
a. To improve the visualization of the clusters
b. To standardize the features and prevent dominance by one feature
c. To ensure the algorithm converges faster
d. To reduce the memory usage of the algorithm
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
82. Which of the following statements about DBSCAN is false?
a. It can automatically detect cluster shapes and sizes
b. It is sensitive to the order of the data points
c. It can handle noise and outliers
d. It does not work well with high-dimensional data
83. What is the limitation of hierarchical clustering for handling large
datasets?
a. It requires specifying the number of clusters beforehand
b. It has a high computational complexity
c. It cannot handle non-linearly separable data
d. It assumes numerical distances between data points
84. Which clustering algorithm is based on connectivity and density of
data points?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
85. Which parameter in hierarchical clustering determines the
merging strategy for clusters?
a. Distance metric
b. Number of clusters
c. Linkage criterion
d. Number of iterations
86. What visualization technique is commonly used to visualize the
clusters generated by clustering algorithms?
a. Scatter plot c. Bar chart
b. Line plot d. Pie chart
87. How does Mean Shift clustering determine the number of
clusters?
a. By iteratively estimating the bandwidth parameter
b. By iteratively merging clusters based on density
c. By minimizing the within-cluster sum of squares
d. By maximizing the silhouette coefficient
88. Which clustering algorithm can handle varying cluster sizes and
densities?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. DBSCAN
d. Spectral clustering
89. Which clustering algorithm is an example of a density-based
algorithm?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
90. Which clustering algorithm does not require specifying the
number of clusters?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Spectral clustering
91. What is the purpose of the linkage parameter in hierarchical
clustering?
a. To specify the distance metric to be used
b. To specify the number of clusters to be formed
c. To specify the merging strategy for clusters
d. To specify the maximum depth of the dendrogram
92. Which algorithm is suitable for clustering textual data?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Latent Dirichlet Allocation (LDA)
93. Which clustering algorithm is appropriate for detecting outliers or
anomalies in data?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
94. Which clustering algorithm is based on graph theory and spectral
decomposition?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Spectral clustering
95. Which clustering algorithm is most suitable for categorical data?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. K-prototypes clustering
96. What is the main drawback of K-means clustering?
a. It cannot handle missing values in the data
b. It is sensitive to the initial choice of centroids
c. It cannot handle non-linearly separable data
d. It requires the number of clusters to be specified beforehand
97. Which Python library provides the implementation of Mean Shift
clustering?
a. PyTorch
b. Keras
c. Scikit-learn
d. TensorFlow
98. Which clustering algorithm is appropriate for high-dimensional
data?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. DBSCAN
d. Affinity propagation
99. In DBSCAN, what does the “min_samples” parameter specify?
a. The maximum distance between two samples for them to be
considered as in the same neighborhood.
b. The minimum number of samples in a neighborhood for a data
point to be considered as a core point
c. The minimum number of clusters to be formed
d. The maximum number of iterations for the algorithm to converge
100. Which clustering algorithm is based on the concept of medoids
instead of centroids?
a. K-means clustering
b. K-medians clustering
c. DBSCAN
d. Agglomerative hierarchical clustering
101. How can the Silhouette coefficient be interpreted?
a. A value close to 1 indicates well-separated clusters
b. A value close to -1 indicates well-separated clusters
c. A value close to 0 indicates well-separated clusters
d. The coefficient cannot be interpreted
102. What is the limitation of K-means clustering when dealing with
categorical data?
a. It cannot handle missing values
b. It assumes numerical distances between data points
c. It cannot handle non-linearly separable data
d. It requires the number of clusters to be specified beforehand
103. Which clustering algorithm is considered more suitable for large
datasets?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Mean Shift
104. How does K-means++ initialization improve the convergence and
performance of K-means clustering?
a. By initializing centroids closer to the actual data points
b. By ensuring an equal number of iterations for each centroid
c. By skipping the initialization step to save memory usage
d. By reducing the number of clusters to be formed
105. Which clustering algorithm uses a density estimation technique to
find cluster centroids?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Affinity propagation
106. Which clustering algorithm works well with categorical data?
a. K-means clustering
b. Agglomerative hierarchical clustering
c. DBSCAN
d. K-modes 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
108. Which clustering algorithm is based on a model-selection method
known as Bayesian Information Criterion (BIC)?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Gaussian Mixture Models (GMM)
109. What is the parameter in DBSCAN that determines whether a
data point is a core point, border point, or noise point?
a. Epsilon c. Metric
b. Min_samples d. Leaf_size
110. Which clustering algorithm is based on the concept of minimizing
the distance between points within a cluster and maximizing the
distance between different clusters?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Agglomerative hierarchical clustering
111. Which algorithm is used in Python for hierarchical clustering
implementation?
a. K-means clustering
b. DBSCAN
c. Hierarchical clustering
d. Agglomerative clustering
112. What is the main objective of hierarchical clustering?
a. To classify data into a fixed number of clusters
b. To find the optimal number of clusters
c. To create a hierarchy of clusters
d. To perform feature selection on the dataset
113. In hierarchical clustering, which method is used to calculate the
distance between clusters?
a. Single linkage
b. Complete linkage
c. Average linkage
d. Ward’s method
114. Which Python library provides hierarchical clustering
implementation?
a. NumPy c. scikit-learn
b. SciPy d. Pandas
115. Hierarchical clustering is only applicable to numerical data.
a. True b. False
116. How does hierarchical clustering handle missing values in the
dataset?
a. Assigns a separate cluster for missing values
b. Ignores rows with missing values
c. Imputes missing values using mean or median
d. Converts missing values into a distinct category
117. Which of the following is not a disadvantage of hierarchical
clustering?
a. Computationally expensive
b. Sensitive to outliers
c. Requires predefined number of clusters
d. Difficult to interpret for large datasets
118. Hierarchical clustering can handle large datasets efficiently.
a. True b. False
119. Which visualization technique is commonly used to represent the
results of hierarchical clustering?
a. Scatter plot c. Dendrogram
b. Line plot d. Heatmap
120. Which Python function is used to perform hierarchical clustering
in SciPy?
a. linkage() c. fit()
b. cluster() d. transform()
121. What is the time complexity of hierarchical clustering?
a. O(n) c. O(n log n)
b. O(n^2) d. O(n^3)
122. In hierarchical clustering, the order of merging clusters does not
affect the final result.
a. True b. False
123. Which Python function is used to cut a dendrogram at a specific
number of clusters in SciPy?
a. cut_tree() c. fit()
b. cluster() d. transform()
124. What is the output of hierarchical clustering?
a. Centroids of clusters
b. Labels of clusters
c. Silhouette coefficients
d. Feature importance scores
125. Which method of hierarchical clustering is more prone to
producing long, elongated clusters?
a. Single linkage
b. Complete linkage
c. Average linkage
d. Ward’s method
126. The hierarchical clustering algorithm is guaranteed to converge to
the global optimum.
a. True b. False
127. Which criterion is used to determine the distance between two
clusters in Ward’s method?
a. Difference in means
b. Difference in variances
c. Difference in sums of squares
d. Difference in medians
128. Which method is used to determine the optimal number of clusters
in hierarchical clustering?
a. Elbow method
b. Silhouette method
c. Dendrogram method
d. Gap statistic
129. Agglomerative clustering is a bottom-up approach.
a. True b. False
130. In hierarchical clustering, what is the maximum number of
clusters that can be formed?
a. n c. n/2
b. n-1 d. ∞
131. Which measure is commonly used to determine the similarity
between two clusters in hierarchical clustering?
a. Mutual information
b. Rand index
c. F-measure
d. Jaccard coefficient
132. Which type of distance matrix is required as input for hierarchical
clustering?
a. Similarity matrix
b. Covariance matrix
c. Euclidean distance matrix
d. Correlation matrix
133. What is the main advantage of hierarchical clustering over other
clustering algorithms?
a. Requires less computational resources
b. Does not require the number of clusters to be predefined
c. Produces more accurate results
d. Can handle categorical data effectively
134. Which library is commonly used for implementing density-based
clustering in Python?
a. Pandas c. SciPy
b. Numpy d. Matplotlib
135. What is the main advantage of density-based clustering algorithms
over other clustering algorithms?
a. They can handle arbitrary cluster shapes
b. They are computationally faster
c. They do not require data pre-processing
d. They do not require distance measures
136. Which of the following is a density-based clustering algorithm?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Gaussian Mixture Models
137. What does DBSCAN stand for?
a. Density-Based Spatial Clustering of Applications with Noise
b. Distance-Based Spatial Clustering of Applications with Noise
c. Distance-Based Silhouette Clustering of Applications with Noise
d. Density-Based Silhouette Clustering of Applications with Noise
138. What are the two main parameters of DBSCAN algorithm?
a. MinPts and Eps
b. K and Eps
c. MinPts and K
d. MinPts and K-neighbors
139. What does the Eps parameter represent in DBSCAN?
a. The minimum number of points required to form a cluster
b. The maximum distance between two points to be considered part
of the same cluster
c. The maximum number of clusters to be formed
d. The maximum number of iterations allowed
140. Which of the following statements about DBSCAN is true?
a. It assigns each data point to a specific cluster
b. It assigns each data point a density value based on its neighbors
c. It can only handle numerical data
d. It cannot handle noise/outliers in the data
141. In DBSCAN, which type of data point is considered noise or
outlier?
a. Data points with a high-density value
b. Data points with a low-density value
c. Data points with a negative-density value
d. Data points with a zero-density value
142. Which Python library is commonly used for data visualization
when working with DBSCAN?
a. Numpy c. Matplotlib
b. Pandas d. Seaborn
143. What is the time complexity of DBSCAN algorithm?
a. O(n) c. O(n log n)
b. O(n^2) d. O(n^2 log n)
144. Which of the following clustering algorithms is sensitive to the
order of data points?
a. K-means clustering
b. Hierarchical clustering
c. DBSCAN
d. Gaussian Mixture Models
145. Which Python library is commonly used to calculate pairwise
distances between data points for DBSCAN?
a. Numpy c. Scikit-learn
b. Pandas d. Scipy
146. What happens when the MinPts parameter is set too high in
DBSCAN?
a. More points will be considered noise
b. More clusters will be formed
c. Fewer clusters will be formed
d. The algorithm will not converge
147. Which data structure is commonly used to store information about
visited/unvisited data points in DBSCAN algorithm?
a. List c. Queue
b. Set d. Stack
148. Which step(s) in DBSCAN algorithm is/are responsible for
assigning data points to clusters?
a. Density-reachability check
b. Density-connected components search
c. Both (a) and (b)
d. Neither (a) nor (b)
149. Which of the following methods can be used to measure the
quality of clustering results?
a. Silhouette score
b. Rand index
c. Davies-Bouldin index
d. All of the above
150. Which Python library is commonly used to calculate silhouette
score for evaluating DBSCAN clustering?
a. Numpy c. Scikit-learn
b. Pandas d. Scipy
151. What is the best choice of MinPts and Eps values for DBSCAN?
a. There is no definitive answer, it depends on the dataset
b. MinPts = 1, Eps = 1
c. MinPts = 2, Eps = 0.5
d. MinPts = 5, Eps = 2
152. How does DBSCAN handle overlapping clusters?
a. It assigns each overlapping data point to multiple clusters
b. It merges the overlapping clusters into a single larger cluster
c. It treats the overlapping data points as noise/outliers
d. It discards the overlapping data points from the clustering process
153. Which type of clustering algorithm is DBSCAN classified as?
a. Supervised clustering
b. Semi-supervised clustering
c. Unsupervised clustering
d. Reinforcement clustering
154. Which of the following statements about DBSCAN is true?
a. It is sensitive to the order of data points
b. It can handle arbitrarily shaped clusters
c. It requires the number of clusters to be specified in advance
d. It is faster than K-means clustering
155. Which step in DBSCAN algorithm is responsible for labeling
noise/outliers in the dataset?
a. Density-reachability check
b. Density-connected components search
c. Cluster assignment
d. None of the above
156. Which module in Python can be used for model evaluation
methods?
a. sklearn c. pandas
b. numpy d. matplotlib
157. Which method can be used to evaluate the accuracy of a
classification model?
a. Mean Absolute Error (MAE)
b. Mean Squared Error (MSE)
c. Confusion Matrix
d. R-squared
158. Which evaluation method is used to assess the performance of a
clustering algorithm?
a. Silhouette score
b. Accuracy score
c. F1 score
d. Log loss
159. Which method can be used to evaluate the performance of a
recommender system?
a. Mean Absolute Error (MAE)
b. Root Mean Squared Error (RMSE)
c. Precision
d. R-squared
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
161. Which evaluation method can be used to evaluate the performance
of a multi-class classification model?
a. Mean Absolute Error (MAE)
b. F1 Score
c. Root Mean Squared Error (RMSE)
d. R-squared
162. Which evaluation method is commonly used for imbalanced
datasets in classification problems?
a. Mean Absolute Error (MAE)
b. Receiver Operating Characteristic (ROC) Curve
c. Log Loss
d. Root Mean Squared Error (RMSE)
163. Which evaluation method can be used to measure the performance
of a regression model that predicts continuous values?
a. F1 Score c. Confusion Matrix
b. R-squared d. Precision
164. Which method can be used to evaluate the performance of a
natural language processing model?
a. Mean Absolute Error (MAE)
b. F1 score
c. Accuracy score
d. BLEU score
165. Which evaluation method is suitable for evaluating the
performance of an anomaly detection model?
a. Mean Absolute Error (MAE)
b. Mean Squared Error (MSE)
c. Receiver Operating Characteristic (ROC) Curve
d. Precision-Recall Curve
166. Which evaluation method can be used to measure how well a
regression model captures the variability in the data?
a. F1 Score
b. R-squared
c. Confusion Matrix
d. Mean Absolute Error (MAE)
167. Which evaluation method is suitable for evaluating the
performance of a time series forecasting model?
a. Mean Absolute Error (MAE)
b. Mean Squared Error (MSE)
c. Root Mean Squared Error (RMSE)
d. All of the above
168. Which evaluation method can be used to assess the performance of
a model that predicts the probability of an event?
a. Mean Absolute Error (MAE)
b. Log loss
c. F1 score
d. R-squared
169. Which evaluation method can be used to assess the performance of
a model that predicts the probability of multiple classes?
a. Mean Squared Error
b. Log Loss
c. Receiver Operating Characteristic Curve
d. Confusion matrix
170. Which evaluation method can be used to measure the performance
of an unsupervised learning algorithm that assigns data points to
clusters?
a. F1 Score
b. Silhouette Score
c. ROC AUC Score
d. Root Mean Squared Error (RMSE)
171. Which evaluation method is suitable for evaluating the
performance of a recommendation system that suggests items to
users?
a. Mean Absolute Error (MAE)
b. Root Mean Squared Error (RMSE)
c. Precision
d. R-squared
172. Which evaluation method can be used to assess the performance of
a model that works with textual data, such as sentiment analysis?
a. F1 Score c. BLEU Score
b. Accuracy Score d. Log Loss
173. Which evaluation method can be used to measure the performance
of a regression model that predicts housing prices?
a. F1 Score
b. R-squared
c. Confusion matrix
d. Receiver Operating Characteristic (ROC) curve
174. Which evaluation method can be used to assess the performance of
a model that assigns probabilities to multiple classes?
a. Log Loss
b. Mean Squared Error (MSE)
c. F1 Score
d. Precision-Recall Curve
175. Which evaluation method can be used to measure how well a
classification model can correctly identify the negative class?
a. Mean Absolute Error (MAE)
b. Receiver Operating Characteristic (ROC) curve
c. Precision
d. R-squared
176. Which evaluation method can be used to assess the performance of
a model that predicts continuous values between 0 and 1?
a. F1 Score
b. R-squared
c. Log Loss
d. Receiver Operating Characteristic (ROC) curve
177. Which evaluation method is suitable for evaluating the
performance of a model that assigns labels to text documents?
a. Mean Absolute Error (MAE)
b. F1 Score
c. Accuracy Score
d. BLEU Score
178. What is a recommender system?
a. A system that suggests similar items to users based on their
preferences.
b. A system that predicts future trends based on historical data.
c. A system that analyzes user behavior to improve website
performance.
d. A system that displays advertisements based on user browsing
history.
179. What are the two main types of recommender systems?
a. Content-based and collaborative filtering.
b. Collaborative filtering and hybrid systems.
c. Collaborative filtering and knowledge-based systems.
d. Hybrid systems and knowledge-based systems.
180. Which type of recommender system analyzes user preferences and
item characteristics to make recommendations?
a. Content-based filtering
b. Collaborative filtering
c. Hybrid filtering
d. Demographic filtering
181. Which algorithm is commonly used in collaborative filtering?
a. K-means clustering
b. Decision tree
c. Singular Value Decomposition (SVD)
d. Naive Bayes classifier
182. How does collaborative filtering make recommendations?
a. By finding similar users and recommending items they have liked
b. By analyzing item characteristics and recommending similar
items
c. By evaluating user preferences and suggesting popular items
d. By considering demographic information and suggesting
personalized items
183. What is the drawback of content-based filtering?
a. It does not consider the opinions of other users
b. It requires a lot of computational resources
c. It only recommends popular items
d. It is difficult to implement in Python
184. What is the drawback of collaborative filtering?
a. It requires a lot of computational resources
b. It cannot handle sparse data
c. It only recommends popular items
d. It is difficult to implement in Python
185. What approach combines the strengths of content-based and
collaborative filtering?
a. Knowledge-based filtering.
b. Hybrid filtering.
c. Demographic filtering.
d. Association rule learning.
186. Which Python library can be used for building recommender
systems?
a. Pandas. c. SciPy
b. NumPy d. All of the above
187. Which Python library is commonly used for matrix factorization
in recommender systems?
a. Pandas c. SciPy
b. NumPy d. Surprise
188. What is the purpose of matrix factorization in recommender
systems?
a. To identify similar items for content-based filtering
b. To identify similar users for collaborative filtering
c. To predict user item ratings in collaborative filtering
d. To calculate item-item similarity in hybrid filtering
189. What is the recall metric in recommender systems evaluation?
a. The percentage of recommended items that are relevant to the
user
b. The percentage of relevant items that are recommended to the
user
c. The percentage of users who rated an item highly
d. The percentage of users who ignored a recommended item
190. What is the purpose of the popularity-based approach in
recommender systems?
a. To recommend popular items to all users
b. To recommend items based on demographic information
c. To recommend items based on content similarity
d. To recommend items that are relevant to the user’s preferences
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
192. What is the collaborative filtering memory-based approach?
a. It uses machine learning algorithms to predict user preferences
b. It stores user-item ratings in a matrix and uses similarities
between users or items to make recommendations
c. It recommends items based on their content similarity
d. It recommends popular items to all users
193. What is the collaborative filtering model-based approach?
a. It uses machine learning algorithms to predict user preferences
b. It stores user-item ratings in a matrix and uses similarities
between users or items to make recommendations
c. It recommends items based on their content similarity
d. It recommends popular items to all users
194. Which machine learning algorithm is commonly used for
collaborative filtering in recommender systems?
a. Linear Regression
b. K-means clustering
c. Decision tree
d. Matrix factorization
195. What is the purpose of evaluation metrics in recommender
systems?
a. To measure the accuracy of recommendations
b. To measure the popularity of recommended items
c. To measure the diversity of recommendations
d. To measure the user satisfaction with the recommendations
196. Which evaluation metric helps measure the diversity of
recommendations?
a. Precision c. F1 score
b. Recall d. Novelty
197. What is the purpose of cross-validation in recommender systems?
a. To split the data into training and testing sets
b. To evaluate the performance of the recommender system
c. To measure the novelty of the recommendations
d. To handle missing data in the user-item matrix
198. In which scenario would you use the popularity-based approach in
recommender systems?
a. When you have no information about user preferences
b. When you want to personalize recommendations
c. When you want to recommend similar items to a user
d. When you want to use demographic information to make
recommendations.
199. In which scenario would you use the content-based approach in
recommender systems?
a. When you have no information about user preferences
b. When you want to personalize recommendations
c. When you want to recommend similar items to a user
d. When you want to use demographic information to make
recommendations
200. In which scenario would you use the collaborative filtering
approach in recommender systems?
a. When you have no information about user preferences
b. When you want to personalize recommendations
c. When you want to recommend similar items to a user
d. When you want to use demographic information to make
recommendations
201. What is the purpose of item-based collaborative filtering?
a. To recommend similar items to a user
b. To recommend items based on user demographics
c. To predict user ratings for items
d. To identify similar users for collaborative filtering
202. What is the main drawback of item-based collaborative filtering?
a. It requires a lot of computational resources
b. It only recommends popular items
c. It cannot handle sparse data
d. It can suffer from the sparsity problem
203. What is the purpose of non-negative matrix factorization in
collaborative filtering?
a. To predict user ratings for items
b. To identify similar items for content-based filtering
c. To overcome the sparsity problem in collaborative filtering
d. To recommend popular items to all users
204. What is the purpose of item-item collaborative filtering?
a. To recommend similar items to a user
b. To recommend items based on user demographics
c. To predict user ratings for items
d. To identify similar users for collaborative filtering
205. What is the purpose of cosine similarity in collaborative filtering?
a. To measure the similarity between items in content-based
filtering
b. To measure the similarity between users in collaborative filtering
c. To predict user ratings for items
d. To recommend popular items to all users
206. What is the purpose of TF-IDF in content-based filtering?
a. To measure the similarity between items.
b. To measure the popularity of items.
c. To predict user ratings for items.
d. To recommend popular items to all users.
207. What is the main advantage of collaborative filtering over content-
based filtering?
a. It does not require user preferences.
b. It provides personalized recommendations.
c. It can handle the cold start problem.
d. It is easier to implement in Python.
208. What is the main advantage of content-based filtering over
collaborative filtering?
a. It does not require user preferences.
b. It provides personalized recommendations.
c. It can handle the cold start problem.
d. It is easier to implement in Python.
209. What is the purpose of the user-based collaborative filtering
method?
a. To recommend similar items to a user.
b. To recommend items based on user demographics.
c. To predict user ratings for items.
d. To identify similar users for collaborative filtering.
210. What is the purpose of the item-based collaborative filtering
method?
a. To recommend similar items to a user.
b. To recommend items based on user demographics.
c. To predict user ratings for items.
d. To identify similar users for collaborative filtering.
211. What is the purpose of the Slope One algorithm?
a. To recommend similar items to a user.
b. To predict user ratings for items.
c. To handle missing data in the user-item matrix.
d. To measure the diversity of recommendations.
212. What is the purpose of the Association Rules algorithm in
recommender systems?
a. To recommend similar items to a user.
b. To predict user ratings for items.
c. To handle missing data in the user-item matrix.
d. To identify patterns in user behavior for recommendation.
213. What is the purpose of the SVD algorithm in recommender
systems?
a. To recommend similar items to a user.
b. To predict user ratings for items.
c. To handle missing data in the user-item matrix.
d. To measure the diversity of recommendations.
214. What is the purpose of the k-NN algorithm in recommender
systems?
a. To recommend similar items to a user.
b. To predict user ratings for items.
c. To handle missing data in the user-item matrix.
d. To measure the diversity of recommendations.
215. What is the purpose of Singular Value Decomposition in
recommender systems?
a. To recommend similar items to a user.
b. To predict user ratings for items.
c. To handle missing data in the user-item matrix.
d. To measure the diversity of recommendations.
216. Which Python library is commonly used for implementing
clustering algorithms?
a. Pandas c. Scikit-learn
b. NumPy d. Matplotlib
217. Which function from sklearn.cluster can be used to create
K-Means clustering in Python?
a. KMeans.fit()
b. sklearn.kmeans()
c. sklearn.cluster.KMeans()
d. KMeans.cluster()
218. Which parameter in K-Means clustering specifies the number of
clusters?
a. clusters
b. n_clusters
c. k_value
d. n_centroids
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_
220. Which clustering algorithm in Scikit-learn does not require
specifying the number of clusters as a parameter?
a. K-Means
b. DBSCAN
c. Agglomerative Clustering
d. Gaussian Mixture Model (GMM)
221. What method in Scikit-learn is used to fit DBSCAN clustering to
the data?
a. fit()
b. train()
c. DBSCAN.fit_predict()
d. DBSCAN.predict()
222. In DBSCAN, what does the parameter eps represent?
a. Number of neighbors
b. Distance threshold
c. Number of clusters
d. Learning rate
223. Which clustering algorithm in Scikit-learn is based on hierarchical
relationships between points?
a. K-Means
b. DBSCAN
c. Agglomerative clustering
d. Spectral clustering
224. What method is used to fit Agglomerative Clustering in Scikit-
learn?
a. fit()
b. train()
c. AgglomerativeClustering.fit_predict()
d. AgglomerativeClustering.predict()
225. Which Python library is commonly used for visualizing clustering
results?
a. Matplotlib c. Seaborn
b. Pandas d. Plotly
226. What function in Matplotlib is often used to plot scatter plots for
visualizing clustered data?
a. plot() c. scatterplot()
b. scatter() d. clusterplot()
227. Which method in Matplotlib is used to set colors for different
clusters in a scatter plot?
a. set_color()
b. set_colors()
c. color()
d. set_facecolor()
228. What function in Matplotlib is used to create a 3D scatter plot?
a. plot_3d() c. scatterplot_3d()
b. scatter_3d() d. plot3D()
229. Which Python library can be used to create interactive
visualizations of clustering results?
a. Matplotlib c. Plotly
b. Seaborn d. Pandas
230. What function in Plotly is used to create a 3D scatter plot for
clustering visualization?
a. plot_3d() c. scatter3D()
b. scatter_3d() d. plot3D()
231. Which Scikit-learn method is used to perform Gaussian Mixture
Model (GMM) clustering?
a. GMM.fit()
b. GaussianMixture.fit()
c. Gaussian.fit()
d. GMM.cluster()
232. What parameter in Gaussian Mixture Model (GMM) represents
the number of components or clusters?
a. components c. n_components
b. clusters d. n_clusters
233. Which method in Scikit-learn is used to predict the cluster labels
after GMM clustering?
a. predict()
b. GMM.predict()
c. GaussianMixture.predict()
d. fit_predict()
234. In clustering evaluation, what metric measures the compactness of
clusters and separation between clusters?
a. Silhouette Score
b. Inertia
c. Homogeneity Score
d. Adjusted Rand Index
235. Which metric is used in K-Means clustering to optimize the
placement of centroids?
a. Silhouette Score
b. Inertia
c. Homogeneity Score
d. Adjusted Rand Index
236. In scikit-learn, what is the primary function used to apply the K-
Means clustering algorithm?
a. apply_kmeans() c. cluster.KMeans()
b. fit_kmeans() d. KMeans.fit()
237. What parameter is crucial in K-Means clustering to determine the
number of clusters?
a. clusters c. k
b. n_clusters d. num_clusters
238. Which method is used to predict cluster labels in K-Means after
fitting the model?
a. predict_labels()
b. cluster_labels()
c. predict()
d. get_cluster_predictions()
239. What does the inertia_ attribute in K-Means represent?
a. Number of iterations
b. Distance between clusters
c. Sum of squared distances of samples to their closest cluster
center
d. Number of clusters
240. Which Python library function is used to implement the DBSCAN
clustering algorithm?
a. cluster.DBSCAN()
b. apply_dbscan()
c. fit_dbscan()
d. DBSCAN.fit()
241. Which Python library is commonly used for hierarchical
clustering?
a. SciPy c. StatsModels
b. Scikit-learn d. NetworkX
242. In hierarchical clustering using SciPy, what function is used to
perform hierarchical/agglomerative clustering?
a. hierarchical()
b. agg_clustering()
c. cluster.hierarchy.linkage()
d. cluster.hierarchy.cluster()
243. What does the method parameter control in hierarchical
clustering using SciPy?
a. Number of clusters
b. Metric for calculating linkage
c. Number of iterations
d. Clustering method (single, complete, average, etc.)
244. Which function is used to visualize the dendrogram in hierarchical
clustering with SciPy?
a. plot_dendrogram()
b. visualize_dendrogram()
c. dendrogram()
d. show_dendrogram()
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
247. Which library provides the AffinityPropagation class for
implementing the Affinity Propagation clustering algorithm?
a. Scikit-learn c. StatsModels
b. SciPy d. TensorFlow
248. In Affinity Propagation, what does the damping parameter
control?
a. Learning rate
b. Convergence speed
c. Number of iterations
d. Distance between exemplars
249. Which Python library provides the SpectralClustering class
for implementing spectral clustering?
a. Scikit-learn
b. SciPy
c. NetworkX
d. TensorFlow
250. Which library is often used for visualizing clusters in Python?
a. Matplotlib
b. Seaborn
c. Plotly
d. All of the above
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 c 51 b 101 a 151 a 201 a
2 b 52 d 102 b 152 a 202 d
3 a 53 c 103 c 153 c 203 a
4 a 54 b 104 a 154 b 204 a
5 c 55 d 105 d 155 c 205 b
6 c 56 c 106 d 156 a 206 a
7 a 57 c 107 b 157 c 207 b
8 d 58 c 108 d 158 a 208 c
9 c 59 a 109 b 159 b 209 d
10 c 60 b 110 a 160 a 210 a
11 a 61 b 111 d 161 b 211 b
12 a 62 d 112 c 162 b 212 d
13 c 63 c 113 c 163 b 213 b
14 c 64 c 114 b 164 d 214 a
15 c 65 a 115 b 165 d 215 b
16 b 66 c 116 a 166 b 216 c
17 a 67 a 117 c 167 d 217 c
18 d 68 d 118 b 168 b 218 b
19 c 69 a 119 c 169 b 219 b
20 b 70 a 120 a 170 b 220 b
21 c 71 a 121 b 171 b 221 c
22 c 72 a 122 b 172 c 222 b
23 c 73 b 123 a 173 b 223 c
24 d 74 c 124 b 174 a 224 c
25 c 75 c 125 a 175 c 225 a
26 b 76 c 126 b 176 c 226 b
27 b 77 d 127 c 177 c 227 d
28 b 78 b 128 c 178 a 228 b
29 c 79 c 129 a 179 a 229 c
30 b 80 b 130 b 180 a 230 c
31 c 81 d 131 b 181 c 231 b
32 c 82 b 132 c 182 a 232 c
33 a 83 b 133 b 183 a 233 a
34 c 84 c 134 c 184 b 234 a
35 c 85 c 135 a 185 b 235 b
36 c 86 a 136 c 186 d 236 d
37 b 87 a 137 a 187 d 237 b
38 d 88 c 138 a 188 c 238 c
39 c 89 c 139 b 189 a 239 c
40 c 90 c 140 b 190 a 240 a
41 b 91 c 141 b 191 d 241 a
42 a 92 d 142 c 192 b 242 c
43 b 93 c 143 b 193 a 243 d
44 b 94 d 144 a 194 d 244 c
45 b 95 d 145 d 195 a 245 a
46 c 96 b 146 c 196 d 246 b
47 c 97 c 147 b 197 b 247 a
48 c 98 d 148 c 198 a 248 b
49 c 99 b 149 d 199 c 249 a
50 c 100 b 150 c 200 b 250 d
CHAPTER 18
Applications of Python
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.
Multiple choice questions
1. In which domain is Python commonly used for data analysis?
a. Astrophysics c. Bioinformatics
b. Geology d. Linguistics
2. Which Python library is widely used for machine learning
applications?
a. Pandas c. TensorFlow
b. Matplotlib d. Requests
3. What does Flask provide in the realm of Python web
development?
a. Machine learning algorithms
b. Web frameworks
c. Database management
d. Server-side scripting
4. Which module is commonly used for web scraping in Python?
a. BeautifulSoup c. Selenium
b. Requests d. All of the above
5. What is the primary purpose of the os module in Python?
a. Data visualization
b. Operating system interactions
c. Machine learning
d. Web development
6. Which Python library is often used for creating interactive
visualizations?
a. NumPy c. TensorFlow
b. Matplotlib d. Pandas
7. What is the primary role of the Requests library in Python?
a. Web development
b. Data analysis
c. Machine learning
d. HTTP requests
8. In Python, which tool is commonly used for automated testing of
web applications?
a. Selenium c. Requests
b. Flask d. Django
9. Which module is used for natural language processing (NLP) in
Python?
a. nltk c. scipy
b. numpy d. matplotlib
10. In Python, what is the purpose of the pygame library?
a. Web development
b. Game development
c. Machine learning
d. Data analysis
11. What does the Tkinter library provide in Python?
a. Web development
b. Game development
c. GUI components
d. Machine learning
12. Which Python library is commonly used for working with
databases?
a. SQLAlchemy c. Requests
b. Matplotlib d. BeautifulSoup
13. In Python, what does the term pickle refer to?
a. Serialization of objects
b. Web development framework
c. Game development library
d. GUI toolkit
14. What is the purpose of the SymPy library in Python?
a. Data visualization
b. Symbolic mathematics
c. Web development
d. Game development
15. Which library in Python is commonly used for numerical
computing?
a. TensorFlow c. NumPy
b. Matplotlib d. Flask
16. In Python, what is the primary role of the BeautifulSoup
library?
a. Web development
b. Data analysis
c. Game development
d. Web scraping
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
18. Which Python library is commonly used for creating and
managing virtual environments?
a. venv
b. Requests
c. NumPy
d. Flask
19. What is the primary purpose of the Pandas library in Python?
a. Web development
b. Data analysis
c. Machine learning
d. Game development
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
22. In Python, which library is commonly used for scientific
computing?
a. NumPy c. SymPy
b. Matplotlib d. Flask
23. What is the primary role of the SciPy library in Python?
a. Web development
b. Data analysis
c. Scientific computing
d. Machine learning
24. Which Python library is commonly used for deep learning
applications?
a. TensorFlow c. NumPy
b. Matplotlib d. Flask
25. What does the term RESTful refer to in the context of Python web
development?
a. A style of software architecture
b. A specific Python library
c. Recursive element for secure transactions
d. Responsive Server Toolkit
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
28. Which library in Python is commonly used for creating 2D and 3D
plots?
a. NumPy c. Requests
b. Matplotlib d. Flask
29. What is the primary role of the logging module in Python?
a. Data analysis
b. Game development
c. Logging messages
d. Web development
30. In Python, what does the term Jupyter refer to?
a. A Python web framework
b. A data visualization library
c. An interactive computing environment
d. A machine learning algorithm
31. What is the primary purpose of the OpenCV library in Python?
a. Data analysis
b. Machine learning
c. Computer vision
d. Web development
32. Which Python library is commonly used for natural language
processing (NLP)?
a. nltk c. Matplotlib
b. NumPy d. Flask
33. What is the role of the random module in Python?
a. Web development
b. Generating random numbers
c. Machine learning
d. Data analysis
34. In Python, what does the term Flask refer to?
a. A data analysis library
b. A web framework
c. A machine learning algorithm
d. A game development library
35. Which Python library is commonly used for handling regular
expressions?
a. NumPy c. re
b. Requests d. SymPy
36. What is the primary purpose of the cryptography library in
Python?
a. Web development
b. Data analysis
c. Cryptographic operations
d. Machine learning
37. Which module in Python is commonly used for dealing with
mathematical functions?
a. Math c. Matplotlib
b. NumPy d. SymPy
38. What is the role of the unittest module in Python?
a. Web development
b. Data analysis
c. Unit testing
d. Machine learning
39. Which Python library is commonly used for creating interactive
dashboards?
a. Django c. Requests
b. Plotly d. Flask
40. In Python, what is the primary purpose of the hashlib module?
a. Web development
b. Data analysis
c. Cryptographic hashing
d. Machine learning
41. What is the purpose of the timeit module in Python?
a. Web development
b. Data analysis
c. Benchmarking code execution time
d. Machine learning
42. In Python, what is the primary purpose of the glob module?
a. Web development
b. Data analysis
c. Pattern matching for file paths
d. Machine learning
43. Which Python library is commonly used for creating interactive
maps and geospatial data visualization?
a. Folium
b. GeoPandas
c. Matplotlib
d. Requests
44. What is the primary purpose of the hashlib module in Python?
a. Web development
b. Data analysis
c. Cryptographic hashing
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
47. In Python, what is the role of the sys module?
a. Web development
b. Data analysis
c. System-specific parameters and functions
d. Machine learning
48. What is the primary purpose of the docker module in Python?
a. Web development
b. Containerization
c. Data analysis
d. Machine learning
49. Which Python library is commonly used for game development?
a. Pandas c. Pygame
b. NumPy d. Requests
50. In Pygame, what function is used to load an image?
a. pygame.display.load_image()
b. pygame.image.load()
c. pygame.load_image()
d. pygame.display.load()
51. What is the purpose of the Pygame module
pygame.display.set_mode()?
a. It sets the display mode for the game
b. It initializes the Pygame display
c. It creates a window with a specified size
d. It loads images onto the display
52. Which function is used to draw a rectangle in Pygame?
a. pygame.draw.rect()
b. pygame.draw.rectangle()
c. pygame.draw_square()
d. pygame.draw.shape()
53. In Pygame, what is the purpose of the pygame.time.Clock()
function?
a. It sets the clock speed of the game
b. It initializes the game clock
c. It measures the time elapsed in the game
d. It controls the frame rate of the game
54. Which Pygame function is used for handling keyboard events?
a. pygame.event.keyboard()
b. pygame.keyboard.get_event()
c. pygame.event.get_keys()
d. pygame.key.get_pressed()
55. What is the purpose of the Pygame function
pygame.sprite.Sprite?
a. It initializes the sprite module in Pygame
b. It creates a new sprite object
c. It loads sprite images onto the display
d. It handles sprite animations
56. In Pygame, which function is used for handling mouse events?
a. pygame.mouse.get_event()
b. pygame.event.mouse()
c. pygame.mouse.get_pressed()
d. pygame.event.get_mouse()
57. What does the Pygame function pygame.mixer.Sound do?
a. It sets the game sound volume
b. It initializes the sound module in Pygame
c. It creates a new sound object
d. It plays background music
58. Which Pygame module is used for collision detection in games?
a. pygame.collision c. pygame.collider
b. pygame.detect d. pygame.sprite
59. What is the purpose of the Pygame function
pygame.font.Font?
a. It sets the font style for the game
b. It initializes the font module in Pygame
c. It creates a new font object
d. It loads text onto the display
60. In Pygame, what does the pygame.quit() function do?
a. It closes the Pygame window
b. It quits the Python interpreter
c. It exits the game loop
d. It initializes the Pygame module
61. Which Pygame function is used to set the position of a sprite?
a. pygame.sprite.set_position()
b. pygame.sprite.position()
c. pygame.sprite.set_pos()
d. pygame.sprite.rect.topleft
62. What does the Pygame function pygame.image.get_rect()
return?
a. A new image object
b. The dimensions of the image
c. The image file format
d. The pixel data of the image
63. In Pygame, what is the purpose of the pygame.mixer.music
module?
a. It handles sprite animations
b. It manages music playback
c. It controls the frame rate of the game
d. It initializes the music module in Pygame
64. Which Pygame function is used to rotate an image?
a. pygame.rotate()
b. pygame.transform.rotate()
c. pygame.image.rotate()
d. pygame.image.transform_rotate()
65. What is the purpose of the Pygame function
pygame.sprite.Group?
a. It creates a new sprite group
b. It manages sprite collisions
c. It initializes the sprite module in Pygame
d. It loads sprites onto the display
66. In Pygame, what does the pygame.event.get() function do?
a. It initializes the event module in Pygame
b. It retrieves all events from the event queue
c. It generates new events
d. It handles keyboard events
67. Which Pygame function is used for scaling an image?
a. pygame.scale()
b. pygame.image.scale()
c. pygame.transform.scale()
d. pygame.image.transform_scale()
68. What is the purpose of the Pygame function
pygame.mouse.get_pos()?
a. It sets the mouse position
b. It gets the current mouse position
c. It initializes the mouse module in Pygame
d. It handles mouse click events
69. In Pygame, which function is used for loading a font?
a. pygame.load_font()
b. pygame.font.load()
c. pygame.load.load_font()
d. pygame.font.load_font()
70. What is the purpose of the Pygame function
pygame.display.flip()?
a. It flips the display vertically
b. It updates the entire display
c. It initializes the display module in Pygame
d. It rotates the display
71. In Pygame, what is the purpose of the
pygame.time.get_ticks() function?
a. It gets the current time in milliseconds
b. It sets the time for the game loop
c. It initializes the time module in Pygame
d. It controls the frame rate of the game
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()
73. What is the purpose of the Pygame function
pygame.event.set_allowed()?
a. It allows specific events to be processed
b. It restricts certain events from being processed
c. It initializes the event module in Pygame
d. It allows all events to be processed
74. In Pygame, what does the pygame.sprite.collide_rect()
function do?
a. It initializes collision detection
b. It checks for collisions between two rectangles
c. It creates a new rectangle object
d. It handles sprite animations
75. What does the Pygame function
pygame.mixer.Sound.play() do?
a. It stops the sound playback
b. It plays the sound
c. It pauses the sound playback
d. It sets the sound volume
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()
77. In Pygame, what is the purpose of the
pygame.mouse.set_visible() function?
a. It sets the visibility of the mouse cursor
b. It initializes the mouse module in Pygame
c. It handles mouse click events
d. It sets the position of the mouse cursor
78. What is the purpose of the Pygame function
pygame.event.post()?
a. It posts events to the event queue
b. It gets the next event from the event queue
c. It initializes the event module in Pygame
d. It handles keyboard events
79. In Pygame, what does the pygame.sprite.Group.update()
function do?
a. It updates the sprite group
b. It initializes sprite updates
c. It updates the display
d. It refreshes the sprite images
80. Which Pygame function is used for loading a sound file?
a. pygame.mixer.load_sound()
b. pygame.sound.load()
c. pygame.mixer.Sound.load()
d. pygame.load_sound()
81. What is the purpose of the Pygame function
pygame.key.get_pressed()?
a. It gets the currently pressed key
b. It initializes the keyboard module in Pygame
c. It checks if a specific key is pressed
d. It gets a list of currently pressed keys
82. In Pygame, what is the purpose of the
pygame.display.set_icon() function?
a. It sets the display icon
b. It initializes the display module in Pygame
c. It creates a new icon object
d. It changes the display resolution
83. Which Pygame function is used for loading a music file?
a. pygame.mixer.music.load()
b. pygame.load_music()
c. pygame.music.load()
d. pygame.mixer.load_music()
84. What does the Pygame function
pygame.mouse.get_pressed() return?
a. The current mouse position
b. The status of all mouse buttons
c. The number of mouse clicks
d. The time since the last mouse click
85. In Pygame, what is the purpose of the
pygame.sprite.Sprite.kill() function?
a. It kills the sprite object
b. It ends the game
c. It stops sprite animations
d. It removes the sprite from the sprite group
86. Which Pygame function is used for loading a font file?
a. pygame.font.load_font()
b. pygame.load_font()
c. pygame.font.Font.load()
d. pygame.load.Font()
87. What is the purpose of the Pygame function
pygame.event.clear()?
a. It clears all events from the event queue
b. It initializes the event module in Pygame
c. It creates a new event object
d. It handles keyboard events
88. In Pygame, what does the pygame.mixer.music.stop()
function do?
a. It stops all sound playback
b. It stops background music playback
c. It sets the music volume to zero
d. It pauses the music playback
89. What is the primary purpose of web scraping in Python?
a. Sending emails
b. Extracting data from websites
c. Creating graphical user interfaces
d. Running machine learning algorithms
90. Which Python library is commonly used for web scraping?
a. NumPy c. BeautifulSoup
b. TensorFlow d. Matplotlib
91. What is the role of the requests library in web scraping?
a. Parsing HTML
b. Making HTTP requests
c. Styling web pages
d. Extracting data from databases
92. In web scraping, what is the purpose of the robots.txt file?
a. It contains the website’s HTML code
b. It specifies the rules for web crawlers
c. It defines the website’s layout and design
d. It is a configuration file for web servers
93. Which of the following is NOT a common challenge in web
scraping?
a. Handling dynamic content
b. Dealing with CAPTCHAs
c. Accessing a website’s database directly
d. Avoiding detection and blocking
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
99. Which of the following is a common ethical consideration in web
scraping?
a. Extracting as much data as possible
b. Ignoring the robots.txt file
c. Scraping sensitive personal information
d. Scraping without the website owner’s consent
100. In web scraping, what is the purpose of the Selenium library?
a. Parsing HTML
b. Making HTTP requests
c. Automating browser interactions
d. Extracting data from APIs
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
102. Which of the following is an example of an anti-scraping technique
used by websites?
a. Providing a well-documented API
b. Using unique and descriptive HTML tags
c. Implementing CAPTCHAs
d. Including a robots.txt file
103. What is the purpose of the BeautifulSoup library in web
scraping?
a. Making HTTP requests
b. Handling dynamic content
c. Parsing and navigating HTML and XML documents
d. Automating browser interactions
104. Which of the following is a common protocol used for web
scraping?
a. FTP c. HTTP
b. SMTP d. SNMP
105. What is the purpose of the HEAD request method in web
scraping?
a. Retrieving the entire content of a web page
b. Checking if a web page exists without retrieving its content
c. Updating the content of a web page
d. Redirecting the client to another URL
106. Which of the following is a potential legal consideration in web
scraping?
a. Scraping publicly available information
b. Scraping for personal use only
c. Scraping without attribution
d. Scraping with the intention of creating a derivative work
107. What is the purpose of the urllib library in web scraping?
a. Parsing HTML
b. Making HTTP requests
c. Handling dynamic content
d. Automating browser interactions
108. Which of the following is a common technique to handle dynamic
content in web scraping?
a. Using a static proxy
b. Executing JavaScript code
c. Ignoring the robots.txt file
d. Increasing the rate of HTTP requests
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
111. Which HTTP status code indicates a successful response in web
scraping?
a. 200 c. 500
b. 404 d. 302
112. What is the purpose of the CSS selector in web scraping?
a. Controlling the appearance of a web page
b. Defining the content type of the HTTP request
c. Selecting HTML elements for extraction
d. Identifying the web browser and operating system
113. Which of the following is a potential challenge in handling
asynchronous web scraping?
a. Slow internet connection
b. Lack of authentication
c. Captchas
d. JavaScript rendering
114. What is the purpose of the pickle module in web scraping?
a. Serializing and deserializing Python objects
b. Parsing HTML
c. Making HTTP requests
d. Executing JavaScript code
115. Which of the following is a common technique to avoid being
blocked during web scraping?
a. Increasing the rate of HTTP requests
b. Using the same user-agent for all requests
c. Ignoring the robots.txt file
d. Scraping during peak hours
116. What is the purpose of the LXML library in web scraping?
a. Making HTTP requests
b. Parsing and navigating HTML and XML documents
c. Automating browser interactions
d. Executing JavaScript code
117. In order to circumvent blocking while scraping the web, what is
the most typical practice?
a. Scraping multiple websites simultaneously
b. Using a large number of proxies
c. Providing inaccurate user-agent information
d. Making frequent and aggressive requests
118. In web scraping, what is the purpose of the hash function?
a. Encrypting data transmitted between the client and server
b. Identifying duplicate data
c. Parsing HTML
d. Controlling the behavior of search engine crawlers
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
120. Which of the following is a common technique to handle the
CAPTCHA challenge in web scraping?
a. Ignoring CAPTCHAs
b. Using a CAPTCHA-solving service
c. Scraping without a user-agent
d. Avoiding the use of proxies
121. What is the purpose of the Scrapy framework in web scraping?
a. Making HTTP requests
b. Parsing and navigating HTML and XML documents
c. Automating browser interactions
d. Streamlining the web scraping process
122. Which of the following is a common technique to handle
pagination in web scraping?
a. Extracting data only from the first page
b. Using a web browser extension
c. Iterating through multiple pages programmatically
d. Ignoring the robots.txt file
123. What is the purpose of the Politeness Policy in web scraping?
a. Defining the layout of a web page
b. Specifying the rules for web crawlers
c. Controlling the speed of HTTP requests
d. Handling dynamic content
124. Which of the following is a potential ethical consideration in web
scraping?
a. Scraping public information
b. Scraping for educational purposes
c. Scraping without attribution
d. Scraping with the website owner’s consent
125. What is the purpose of the Splash library in web scraping?
a. Making HTTP requests
b. Parsing and navigating HTML and XML documents
c. Automating browser interactions
d. Handling JavaScript rendering
126. In web scraping, what is the purpose of the CSS library?
a. Controlling the appearance of a web page
b. Parsing HTML
c. Selecting HTML elements for extraction
d. Identifying the web browser and operating system
127. Which of the following is a common challenge in web scraping
mobile applications?
a. Handling dynamic content
b. Avoiding detection and blocking
c. Ignoring the robots.txt file
d. Using the same user-agent for all requests
128. What is the purpose of the PhantomJS browser in web scraping?
a. Making HTTP requests
b. Parsing and navigating HTML and XML documents
c. Handling JavaScript rendering
d. Automating browser interactions
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
130. In business applications, which Python library is commonly used
for data visualization and plotting?
a. Pandas c. NumPy
b. Matplotlib d. Requests
131. What is the primary purpose of using Python in business
analytics?
a. Game development
b. Data analysis and visualization
c. Web development
d. Machine learning
132. Which Python library is frequently employed for machine
learning tasks in business applications?
a. Flask c. TensorFlow
b. Django d. PyTorch
133. In business applications, which module is commonly used for
interacting with databases using Python?
a. sqlite3 c. os
b. json d. requests
134. What role does Python play in automating business processes?
a. Generating random numbers
b. Sending HTTP requests
c. Developing web applications
d. Streamlining repetitive tasks and workflows
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
138. How can Python be employed for text analysis in business
applications?
a. By creating GUI applications
b. By using the speech_recognition module
c. By applying NLP techniques
d. By encoding and decoding data
139. Which Python library is commonly used for sending emails in
business applications?
a. email c. poplib
b. smtplib d. imaplib
140. What is the role of Python in supply chain management in
business?
a. Generating invoices
b. Analyzing and optimizing logistics data
c. Creating web applications
d. Developing mobile applications
141. In business applications, which Python library is commonly used
for creating interactive dashboards?
a. Plotly c. Tkinter
b. PyQt d. wxPython
142. How can Python be utilized for financial modeling in business?
a. By creating animations
b. By analyzing and predicting financial trends
c. By generating random numbers
d. By creating virtual reality applications
143. Which Python library is commonly used for accessing and
manipulating SQL databases in business applications?
a. sqlite3 c. pandas
b. pymysql d. requests
144. How does Python contribute to marketing analytics in business
applications?
a. By creating 3D visualizations
b. By analyzing customer sentiment in social media data
c. By developing mobile applications
d. By encrypting and decrypting data
145. What is the role of Python in risk management in business
applications?
a. By generating random numbers
b. By analyzing and mitigating potential risks
c. By creating web applications
d. By developing mobile games
146. In business applications, how can Python be used for human
resources management?
a. By creating virtual reality simulations
b. By analyzing employee performance data
c. By generating 2D graphics
d. By developing mobile applications
147. What is the significance of Python in business intelligence (BI)?
a. By generating QR codes
b. By creating web servers
c. By analyzing and visualizing data to make informed business
decisions
d. By creating machine learning models
148. How can Python be employed for sentiment analysis in business
applications?
a. By creating 3D animations
b. By analyzing text data to determine sentiment
c. By developing mobile applications
d. By encoding and decoding data
149. Which Python library is commonly used for web scraping in
business applications?
a. Scrapy b. BeautifulSoup
c. Flask d. Django
150. How does Python contribute to project management in business
applications?
a. By creating virtual reality simulations
b. By analyzing project timelines and resource allocation
c. By generating random numbers
d. By creating mobile games
151. In business applications, how can Python be utilized for inventory
management?
a. By creating 3D visualizations
b. By analyzing and optimizing inventory data
c. By developing mobile applications
d. By encrypting and decrypting data
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
154. What is the role of Python in quality assurance in business
applications?
a. By generating random numbers
b. By analyzing and improving software quality
c. By creating web applications
d. By developing mobile applications
155. In business applications, which Python library is commonly used
for creating interactive data visualizations?
a. Seaborn c. Flask
b. Django d. Requests
156. How can Python be employed for customer segmentation in
business applications?
a. By creating virtual reality simulations
b. By analyzing customer data and categorizing into groups
c. By developing mobile applications
d. By encrypting and decrypting data
157. What role does Python play in financial reporting in business
applications?
a. By creating virtual reality simulations
b. By analyzing and presenting financial data
c. By generating random numbers
d. By creating mobile games
158. In business applications, how can Python be utilized for risk
assessment?
a. By creating virtual reality simulations
b. By analyzing and evaluating potential risks
c. By generating random numbers
d. By creating mobile applications
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
161. In business applications, which module is commonly used for
handling dates and times in Python?
a. datetime c. calendar
b. time d. pytz
162. What is the role of Python in customer retention strategies in
business applications?
a. By creating virtual reality simulations
b. By analyzing customer behavior and implementing strategies for
customer loyalty
c. By generating random numbers
d. By creating mobile applications
163. How can Python be employed for A/B testing in business
applications?
a. By creating virtual reality simulations
b. By analyzing and comparing different versions of a product or
service
c. By generating random numbers
d. By developing mobile applications
164. In business applications, which Python library is commonly used
for statistical analysis?
a. Scipy c. Matplotlib
b. Pandas d. Seaborn
165. How can Python be utilized for fraud detection in business
applications?
a. By creating virtual reality simulations
b. By analyzing patterns and anomalies in financial transactions
c. By generating random numbers
d. By creating mobile applications
166. What is the role of Python in employee performance analytics in
business applications?
a. By creating virtual reality simulations
b. By analyzing and evaluating employee performance data
c. By generating random numbers
d. By developing mobile applications
167. In business applications, how can Python be used for optimizing
advertising campaigns?
a. By creating virtual reality simulations
b. By analyzing data to improve targeting and performance
c. By generating random numbers
d. By creating mobile applications
168. How does Python contribute to supply chain optimization in
business applications?
a. By creating virtual reality simulations
b. By analyzing and streamlining logistics and inventory data
c. By generating random numbers
d. By creating mobile applications
169. In business applications, which Python library is commonly used
for time series forecasting?
a. Pandas c. Matplotlib
b. Statsmodels d. Prophet
170. How can Python be utilized for sentiment analysis in customer
feedback for business applications?
a. By creating virtual reality simulations
b. By analyzing text data to determine sentiment
c. By developing mobile applications
d. By encoding and decoding data
171. What is the role of Python in e-commerce analytics in business
applications?
a. By creating virtual reality simulations
b. By analyzing customer behavior and optimizing online shopping
experiences
c. By generating random numbers
d. By creating mobile applications
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
174. Which Python library is commonly used for audio processing?
a. PyDub c. TensorFlow
b. NumPy d. Flask
175. What does the term FFT stand for in the context of audio
processing?
a. Fast Fourier Transform
b. Frequency Filtering Technique
c. File Format Translation
d. Full Functionality Test
176. Which module in Python is commonly used for playing sound?
a. soundplay c. audiofile
b. playsound d. soundpy
177. In video processing, which library is widely used for computer
vision tasks?
a. OpenCV c. PyDub
b. Matplotlib d. MoviePy
178. What is the purpose of the PyDub library in Python?
a. Image processing
b. Audio processing
c. Video processing
d. Text processing
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
181. In audio processing, what does resampling refer to?
a. Changing the volume of audio
b. Changing the pitch of audio
c. Changing the sample rate of audio
d. Changing the file format of audio
182. Which Python library is commonly used for speech recognition?
a. SpeechRecognition
b. PyAudio
c. WaveLib
d. AudioRecognition
183. What is the purpose of the pydub.silence module in PyDub?
a. Add silence to audio
b. Remove silence from audio
c. Analyze silence in audio
d. Convert silence to noise
184. Which method in PyDub is used to concatenate two audio files?
a. concat c. merge
b. combine d. append
185. What does the term spectrogram represent in audio processing?
a. A visual representation of the audio signal’s frequency content
over time
b. A measure of audio loudness
c. The duration of an audio file
d. A type of audio filter
186. Which module in PyDub is used to generate tones or frequencies?
a. pydub.tones
b. pydub.generate
c. pydub.frequency
d. pydub.sine
187. What is the purpose of the cv2.VideoCapture class in
OpenCV?
a. Capture images
b. Capture video frames
c. Edit images
d. Record audio
188. Which method is used for saving a video file in MoviePy?
a. save_video
b. export
c. write_video
d. record
189. In video processing, what is frame rate?
a. The number of pixels in a frame
b. The number of frames per second
c. The resolution of a video
d. The duration of a video
190. What is the purpose of the cv2.resize function in OpenCV?
a. Change the frame rate of a video
b. Resize images
c. Crop video frames
d. Adjust video brightness
191. Which method is used for adding text to a video in MoviePy?
a. add_text c. insert_text
b. text_overlay d. write_text
192. What is the primary function of the cv2.VideoWriter class in
OpenCV?
a. Read video frames
b. Write video frames to a file
c. Display video frames
d. Convert video frames to images
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
195. Which Python library is commonly used for creating visualizations
and plots from data?
a. Matplotlib c. VisualPy
b. PyPlot d. Plotly
196. What does the term chroma refer to in audio processing?
a. Loudness c. Color
b. Pitch d. Tempo
197. In audio processing, what is pitch shifting?
a. Changing the volume of audio
b. Changing the pitch of audio
c. Changing the sample rate of audio
d. Changing the file format of audio
198. Which method in PyDub is used to export audio to a different file
format?
a. export c. convert
b. save_as d. export_as
199. What is the purpose of the cv2.split function in OpenCV?
a. Split audio channels
b. Split video frames
c. Split RGB channels in an image
d. Split frequency bands in audio
200. In audio processing, what does stereo refer to?
a. Mono sound
b. Surround sound
c. Dual-channel sound
d. High-frequency sound
201. Which method in PyDub is used to apply fade-in and fade-out
effects to audio?
a. fade c. add_fade
b. apply_fade d. fade_in_out
202. What is the purpose of the cv2.cvtColor function in OpenCV?
a. Resize images
b. Convert images to grayscale
c. Adjust image brightness
d. Apply filters to images
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
206. Which file format is commonly used for exchanging 3D CAD
models and is often supported by Python libraries?
a. JPEG c. GIF
b. STL d. PNG
207. What is the purpose of the ezdxf library in Python CAD
applications?
a. 3D modeling
b. 2D drawing and DXF file manipulation
c. Rendering images
d. Animation in CAD
208. Which Python library is commonly used for creating 3D
visualizations and interactive plots?
a. Matplotlib c. PyViz
b. Plotly d. VizPy
209. What does the term BIM stand for in the field of CAD?
a. Building Information Modeling
b. Binary Image Mapping
c. Basic Implementation Model
d. Block Indexing Mechanism
210. Which Python library is often used for parametric design and
generative modeling?
a. PySolid c. ParaCAD
b. GenerPy d. ParametricLib
211. In CAD, what does CAM stand for?
a. Computer-Aided Modeling
b. Computer-Aided Manufacturing
c. CAD Analysis Module
d. Computational Algorithmic Modeling
212. Which Python library provides functionality for creating and
manipulating 3D geometry?
a. PyGeo c. GeoCAD
b. 3DLib d. CAD3D
213. What is the purpose of the pyDXF library in Python?
a. 3D modeling
b. Drawing and manipulating DXF files
c. Animation in CAD
d. Parametric design
214. Which Python library is commonly used for creating interactive
3D applications and games?
a. PyOpenGL c. 3DGameLib
b. CAD3D d. OpenCAD
215. In CAD, what is the purpose of the extrusion operation?
a. Creating 2D sketches
b. Converting 3D models to 2D
c. Extending a 2D shape into a 3D object
d. Applying textures to a 3D model
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
218. Which Python library is commonly used for scripting and
automating tasks in AutoCAD?
a. PyAutoCAD
b. AutoScript
c. CADScript
d. AutoPy
219. In CAD, what is the purpose of the boolean operations on shapes?
a. Changing the color of shapes
b. Combining or subtracting shapes to create new shapes
c. Creating 2D sketches
d. Converting 3D models to 2D
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
224. Which Python library is commonly used for creating 3D
animations in CAD?
a. Py3DAnimation
b. AnimationCAD
c. CADAnim
d. PyAnimation3D
225. What is the purpose of the pyCADCAMLib library in Python CAD
applications?
a. 3D modeling
b. Computer-Aided Design and Manufacturing
c. CAD file conversion
d. Custom CAD scripting
226. In CAD, what is the primary function of the spline curve?
a. Creating geometric shapes
b. Representing complex curves
c. Extruding 2D shapes
d. Applying boolean operations on shapes
227. Which Python library is commonly used for creating interactive
3D visualizations for scientific and engineering data?
a. PyViz
b. VizPy
c. SciPy3D
d. PySciViz
228. What is the purpose of the pyCADModel library in Python?
a. Creating 2D sketches
b. Generating CAD models from images
c. 3D modeling
d. CAD file conversion
229. In CAD, what does associative modeling mean?
a. Creating 2D sketches
b. Designing based on parameters and constraints
c. Creating parametric models
d. Extruding 2D shapes
230. Which Python library is often used for converting CAD files to
different formats?
a. CADConvert
b. PyCADConverter
c. ConvertLib
d. CADFileConvert
231. In CAD, what is the purpose of the offset operation on curves?
a. Extruding curves into 3D
b. Creating a duplicate of a curve at a specified distance
c. Combining multiple curves
d. Changing the color of curves
232. Which Python library is commonly used for creating parametric
designs and generative art?
a. PyCADGen c. ParaDesign
b. GenerArt d. CADArt
233. Which Python library is commonly used for developing embedded
systems applications?
a. PyEmbedded c. EmbedLib
b. MicroPython d. PyMicro
234. What is the primary advantage of using MicroPython in
embedded systems?
a. Large memory footprint
b. Compatibility with desktop Python
c. Real-time operating system support
d. Small memory footprint
235. In the context of embedded systems, what is firmware?
a. Hardware components
b. Software that controls hardware
c. Python programming language
d. Middleware components
236. Which Python module is commonly used for accessing hardware-
level functionalities in embedded systems?
a. os c. machine
b. sys d. hardware
237. What does the term GPIO stand for in embedded systems?
a. General Purpose Input Output
b. Graphical Python Input Output
c. Global Processing Input Output
d. Generic Python Input Output
238. Which Python library is often used for communication between
microcontrollers and sensors in embedded systems?
a. PySerial c. SerialLib
b. MicroComm d. CommPy
239. What is the purpose of the uasyncio module in MicroPython?
a. Asynchronous input/output operations
b. Synchronous input/output operations
c. USB communication
d. UART communication
240. In embedded systems, what is flash memory used for?
a. Temporary storage of data
b. Storing firmware and program code
c. Displaying graphical content
d. Real-time data processing
241. Which Python library is commonly used for interfacing with
sensors in embedded systems?
a. PySensor c. MicroSensors
b. SensorLib d. PyInterfacer
242. In MicroPython, what is the purpose of the machine.Pin class?
a. Representing mathematical operations
b. Interfacing with hardware pins
c. Managing network connections
d. Defining custom classes
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
246. Which communication protocol is commonly used for wireless
communication in embedded systems?
a. SPI c. Bluetooth
b. UART d. I2C
247. What is the primary purpose of the machine.UART class in
MicroPython?
a. Controlling GPIO pins
b. Managing asynchronous operations
c. Interfacing with sensors
d. Serial communication with peripherals
248. In embedded systems, what is the role of an interrupt?
a. Halting program execution
b. Triggering a specific function in response to an event
c. Generating random numbers
d. Managing flash memory
249. Which MicroPython module is commonly used for working with
the file system in embedded devices?
a. os c. file
b. sys d. filesystem
250. What does the term PWM stand for in embedded systems?
a. Pulse Width Modulation
b. Programming with Microcontrollers
c. Peripheral Wiring Mechanism
d. Power Management
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 c 51 c 101 a 151 b 201 a
2 c 52 a 102 c 152 b 202 b
3 b 53 b 103 c 153 b 203 a
4 d 54 d 104 c 154 b 204 a
5 b 55 b 105 b 155 a 205 b
6 b 56 c 106 c 156 b 206 b
7 d 57 c 107 b 157 b 207 b
8 a 58 d 108 b 158 b 208 b
9 a 59 c 109 a 159 b 209 a
10 b 60 a 110 c 160 b 210 a
11 c 61 d 111 a 161 a 211 b
12 a 62 b 112 c 162 b 212 a
13 a 63 b 113 d 163 b 213 b
14 b 64 b 114 a 164 a 214 a
15 c 65 a 115 b 165 b 215 c
16 d 66 b 116 b 166 b 216 a
17 a 67 c 117 b 167 b 217 b
18 a 68 b 118 b 168 b 218 a
19 b 69 b 119 b 169 d 219 b
20 a 70 b 120 b 170 b 220 a
21 c 71 a 121 d 171 b 221 b
22 a 72 d 122 c 172 b 222 a
23 c 73 a 123 c 173 b 223 c
24 a 74 b 124 c 174 a 224 a
25 a 75 b 125 d 175 a 225 b
26 a 76 b 126 a 176 b 226 b
27 b 77 a 127 b 177 a 227 a
28 b 78 a 128 c 178 b 228 c
29 c 79 a 129 a 179 b 229 c
30 c 80 c 130 b 180 d 230 b
31 c 81 d 131 b 181 c 231 b
32 a 82 a 132 c 182 a 232 a
33 b 83 a 133 a 183 b 233 b
34 b 84 b 134 d 184 d 234 d
35 c 85 d 135 b 185 a 235 b
36 c 86 c 136 b 186 d 236 c
37 a 87 a 137 b 187 b 237 a
38 c 88 b 138 c 188 b 238 a
39 b 89 b 139 b 189 b 239 a
40 c 90 c 140 b 190 b 240 b
41 c 91 b 141 a 191 c 241 b
42 c 92 b 142 b 192 b 242 b
43 a 93 c 143 b 193 a 243 c
44 c 94 b 144 b 194 b 244 b
45 a 95 b 145 b 195 a 245 b
46 a 96 b 146 b 196 c 246 c
47 c 97 c 147 c 197 b 247 d
48 b 98 b 148 b 198 a 248 b
49 c 99 c 149 a 199 c 249 a
50 b 100 c 150 b 200 c 250 a
CHAPTER 19
Python Error Finding MCQ
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 {
2. Which of the following options correctly fixes the error in this
code?
x = 17
y = 17
if x = y
print("x is equal to y")
else:
print("x is not equal to y")
a. if (x=y) c. if (x==y)
b. if (x=y): d. if x==y :
3. Which of the following options correctly fixes the error in this
code?
for i in range(5):
print(i)
a. The print statement should be indented under the for loop
b. The range function should be range(1, 6)
c. The loop variable should be defined as for i in range(1, 6):
d. No Error
4. Identify the error in the following code:
def concatenate_strings(str1, str2):
result = str1 + str2
return result
print(concatenate_strings("Hello", "World",
"!"))
a. The return statement should be return str1 + “ “ + str2.
b. No Error
c. Can’t use result as a variable
d. The function call should be concatenate_strings(“Hello”,
“World”) without the third argument
5. Which of the following options correctly fixes the error in this
code:
if x = 10
print("hello")
a. if x == 10
b. No Error
c. if else x = 10:
d. if x == 10:
6. Which of the following options correctly fixes the error in this
code:
def display_result(result):
if result > 50
print("Pass")
else:
print("Fail")
a. if result >= 50
b. def display result(“result”):
c. if result > 50 :
d. No Error
7. What will happen when you run this code:
result = 10 / 0
print(result)
a. It will print ‘Infinity’
b. It will print ‘Error: Division by zero’
c. It will print ‘0’
d. It will crash with a runtime error
8. Identify the error in the following code:
1. def multiply(a, b)
2. result = a * b
3. return result
a. No error
b. Missing colon after def multiply(a, b)
c. Missing indentation in line 2
d. Missing return statement
9. Identify the error in the following code:
1. def square(x)
2. return x ** 2
a. No error
b. Missing colon after def square(x)
c. Missing indentation in line 2
d. Both b) and c)
10. Identify the error in the following code:
1. name = "John"
2. age = 25
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 a string (str(age)) in the print statement
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
12. Identify the error in the following code:
1. numbers = [1, 2, 3, 4, 5]
2. result = product(numbers)
3. print("Product of numbers:", result)
a. No error
b. Incorrect indentation in line 3
c. Undefined function product
d. Both b) and c)
13. Identify the error in the following code:
1. def square(x):
2. return x ** 2
3. result = square(4)
a. No error
b. Missing colon after def square(x)
c. Incorrect indentation in line 2
d. Missing print statement for result
14. Identify the error in the following code:
1. x = 5
2. y = "2"
3. z = x + y
a. No error
b. Missing colon after z = x + y
c. Type error - cannot concatenate str and int
d. Incorrect indentation in line 3
15. Identify the error in the following code:
def greet(name):
print("Hello", name)
greet("Alice", "Bob")
a. Missing parentheses after the function name
b. Too many arguments passed to the function
c. Incorrect indentation within the function
d. No error
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
17. Identify the error in the following code:
while True
print("This will print forever")
a. No error
b. Incorrect indentation within the loop
c. Missing colon after the while statement
d. Both (b) and (c)
18. Identify the error in the following code:
try:
result = 10/ 0
except ZeroDivisionError:
print("Cannot divide by zero")
a. No error
b. Missing finally block
c. Incorrect indentation within the try block
d. The code will not catch the ZeroDivisionError
19. Identify the error in the following code:
def my_function(x):
y = x * 2
return y
result = my_function(5)
print(y)
a. Missing colon after the function definition
b. Using a variable outside its scope
c. Indentation error
d. No error
20. Identify the error in the following code:
i = 0
while i < 5:
print(i)
i = i
a. The loop will never terminate
b. Missing increment of i within the loop
c. Indentation error
d. Both (a) and (b)
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
32. Identify the error in the following code:
names1 = ['Amir', 'Bala', 'Charles']
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])
35. What is the error in the following Python code snippet:
my_list = [1, 2, 3, 4]
print(my_list[4])
a. Out of index error
b. Missing quotes around the index in `my_list[4]`
c. No error
d. Missing colon after `my_list = [1, 2, 3, 4]`
36. What is the error in the following Python code snippet:
name = "Alice"
print("Hello + name!")
a. Incorrect string concatenation
b. Missing quotes around `name` in `print(“Hello, name!”)`
c. Missing parentheses in `print(“Hello, name!”)`
d. No error
37. What is the error in the following Python code snippet:
num1 = input("Enter a number: ")
result = num1 * 2
print(result)
a. Incorrect multiplication syntax
b. Missing type casting for input
c. Missing parentheses around the input string
d. No error
38. What is the error in the following Python code snippet:
a = 5
b = "Hello"
print(a + b)
a. Missing parentheses in `print(a + b)`
b. Incorrect addition of integer and string
c. Incorrect variable assignment
d. No error
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):
45. Choose the corrected version of the code below:
x = 5
y = x + "5"
print(y)
a. x = 5
y = string(x) + “5”
print(y)
b. x = 5
y=x+5
print(y)
c. x = ‘5’
y = x + “5”
print(y)
d. x = 5
y = int(x) + “5”
print(y)
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
94. Identify the error in the following code:
value = input("Enter a number:")
if value.isdigit()
print("Numeric value entered.")
else:
print("Non-numeric value entered.")
a. if value.isdigit():
b. if value.isnumeric():
c. if isdigit(value):
d. both (a) and (b)
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
97. Choose the corrected version of the code below:
def add(x, y):
return x + y
print(add(3, 4)
a. def add(x):
return x + y
print(add(3, 4))
b. def add(x, y):
return x + y
print(add(3, 4))
c. def add(x, y):
return x + y
print(add(3 + 4);
d. def add(x + y):
return x + y
print(add(3, 4)
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”)
106. 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. def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
return True;
else:
return False
b. def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > = a:
return True
else:
return False
c. def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > a:
return True
else:
return False
d. def is_triangle(a, b, c):
if a + b > c and a + c > b and b + c > a
return True
else:
return False
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)
113. Identify the error in the following code:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num > 2
print(num)
a. if num > “2”:
print(num)
b. if num > 2;
print(num)
c. if num > 2:
print(num);
d. if num > 2
print(num);
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”)
116. Identify the error in the following code:
value = "hello"
if value == "world":
print("Greetings!")
elif value = "hello":
print("Hello!")
else:
print("Goodbye!")
a. value = “hello”:
if value == “world”:
print(“Greetings!”)
elif value == “hello”:
print(“Hello!”)
else:
print(“Goodbye!”)
b. value = “hello”;
if value == “world”:
print(“Greetings!”)
elif value == “hello”:
print(“Hello!”)
else:
print(“Goodbye!”);
c. value = “hello”
if value == “world”:
print(“Greetings!”)
elif value == “hello”:
print(“Hello!”)
else:
print(“Goodbye!”)
d. No Error
117. Identify the error in the following code:
age = 20
if age > 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child"
a. age = 20
if age > 18:
print(“Adult”)
elif age > 12:
print(“Teenager”)
else:
print(“Child”)
b. age = 20
if age > 18:
printf(“Adult”)
elif age > 12:
printf(“Teenager”)
else:
printf(“Child”)
c. age == 20
if age > 18:
print(“Adult”)
elif age > 12:
print(“Teenager”)
else:
print(“Child”)
d. age = 20
if age > 18:
print(“Adult”)
elif age > 12:
print(“Teenager”)
else:
print(“Child”)
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”)
122. Identify the error in the following code:
score = 85
if score >= 90
print("Excellent Work")
a. No Error
b. if score => 90:
print(“Excellent Work”)
c. if score >= 90:
print(“Excellent Work”)
d. elif score >= 90:
print(“Excellent Work”)
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)
129. What will be the output after the following statements:
x=[1,2,3,4,5]
x.include(6,7,8)
print(x)
a. No Error
b. x.extend([6,7,8])
c. x.append(6,7,8)
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
140. Identify the error in the following code:
count = 0
while count < 5:
print(count)
count++
a. No Error
b. count += 1
c. count = count + 1
d. both (b) and (c)
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
142. Identify the error in the following code:
name = "John"
if name == "John":
print("Hello, John!")
else
print("Who are you?")
a. No Error
b. else:
print(“Who are you?”)
c. elif name != “John”:
print(“Who are you?”)
d. both (b) and (c)
143. Identify the error in the following code:
number = 10
if number > 60
print("Number is greater than 60")
else:
print("Number is not greater than 60")
a. No Error
b. if number > 60:
print(“Number is greater than 60”)
c. elif number == 60:
print(“Number is greater to 60”)
d. if number => 60
print(“Number is greater than 60”)
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
145. Identify the error in the following code:
temperature = 30
if temperature < 0:
print("Freezing")
else if temperature >= 0 and temperature < 10
print("Cold")
elif temperature >= 10 and temperature < 20:
print("Moderate")
else:
print("Warm")
a. No Error
b. elif temperature => 0 and temperature < 10:
print(“Cold”)
c. elif temperature >= 0 and temperature < 10:
d. print(“Cold “)
both (b) and (c)
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)
150. Identify the error in the following code:
x = 5
y = "Hello"
z = x + y
a. No Error
b. z = str(x) + y
c. z = x + int(y)
d. both (b) and (c)
151. Identify the error in the following code:
def is_positive(num):
if num > 0
return True
else:
return False
a. No Error
b. if num > 0:
return true
c. if num > 0
return True
d. both (b) and (c)
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)
153. Identify the error in the following code:
x = 10
y = 5
if x > y:
print(x + " is greater than " + y)
else:
print(x + " is less than " + y)
a. print(str(x) + “ is greater than “ + str(y))
b. print(f”{x} is greater than y”)
c. print(x , “ is greater than “ + y)
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)
163. Identify the error in the following code:
def print_even_numbers(numbers):
while num in numbers:
if num % 2 == 0:
print(num)
a. No Error
b. for num in numbers:
if num % 2 == 0:
print(num)
c. while num in numbers:
if num % 2 == 0:
print(num)
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):
179. Choose the corrected version of the code below:
x = 21
y = x + "43"
print(y)
a. y = string(x) + 43
b. y = x + int(“ 43”)
c. y = int(x) + “43”
d. No Error
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)
186. What will be the output after the following statements:
a=[-3, -1,0,1,3]
print([a[x] for x in a])
a. No Error
b. print([a(x) for x in a])
c. print([a(x) , for x in a])
d. print([a(x) : for x in a])
187. What will be the output of the following statements?
a=[' today ' , ' tomorrow ' , 'not now ']
print ([x .strip() for x in a])
a. No Error
b. print ([x .strip() for x is a])
c. print ([strip(x) for x in a])
d. print ([x .strip() ; for x in a])
188. What will be the output of the following statements:
a=[ ]
b=[0,1,2,3] , [4,5,6,7], [8,9,10,11]
for i in range(4)
a .append([row[i] for row in b])
print(a)
a. No Error
b. for i in range(4):
a .append([row[i] for row in b])
print(a)
c. for i in range(4)
a .append([row(i) for row in b])
print(a)
d. for i in range(4)
a .append([( row[i] ) for row in b])
print(a)
189. What will be the output of the following statements:
a=[[0,1,2,3],[4,5,6,7],[8,9,10,11]]
print(zip(*a))
a. No Error
b. print(list(zip(*a)))
c. print(list(zip(&a)))
d. print(zip(a))
190. What will be the output of the following statements:
a=[0,1,2,3]
a.del()
print (a)
a. No Error c. del (a)
b. del a d. Both (b) and (c)
191. Which of the following options correctly fixes the error in this
code:
def remove_duplicates(lst):
return list(set(lst))
a. No Error
b. return set(lst).sort()
c. return list(lst).unique()
d. return list(unique(lst))
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:
193. Identify the error in the following code:
def count_lowercase_letters(s):
count = 0
for char in s:
if char == islower():
count += 1
return count
a. No Error
b. if char == char.lower():
c. if char.islower():
d. both (b) and (c)
194. What will be the output after the following statements?
x=[15,45,85,95]
print(x(3)-x(1))
a. No Error
b. print(x[3]-x[1])
c. print((x(3)) – (x(1)))
d. both b) and c)
195. Identify the error in the following code:
def double(x):
return X * 2
print("Double of 5 is:", double(5))
a. No Error
b. return x ** 2
c. return x + 2
d. return x * 2
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()
197. Identify the error in the following code:
def calculate_area(length, width):
return length ** width
a. No Error
b. return length + width
c. return length * width
d. return length / width
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
210. Identify the error in the following code:
def find_product(numbers):
product = 1
for num in numbers:
product *== num
return product
print("Product is:", find_product([2, 3, 4,
5]))
a. No Error
b. product *= num
c. product = product * num
d. both (b) and (c)
211. Identify the error in the following code:
def check_vowel(character):
vowels = ['a', 'e', 'i', 'o', 'u']
if character.lower() in vowels:
return True
else:
return False
print(check_vowel('A'))
a. No Error
b. if character in vowels:
c. if lower(character) in vowels:
d. if character.smallcase() in vowels:
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)
223. Identify the error in the following code:
arraylist = [1,1,14,5643,23,543,6,12]
for x in arraylist:
if x > 2
print(x)
a. if x > “2”:
print(x)
b. if x > 2;
print(x)
c. if x > 2:
print(x);
d. if x > 2
print(x);
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:
225. Identify the error in the following code:
s = "Day"
if s == "Day":
print("Have a Good Day ")
elif s = "Evening":
print("Good Evening")
else:
print("Good Night!")
a. elifs == “ Evening “:
b. else if s == Evening :
c. elif s == “Evening”:
d. No Error
226. Identify the error in the following code:
age = 2
if age > 12
print("Teenager")
elif age < 5:
print("infant")
else:
print("Kid")
a. No Error
b. if age > 12:
print(“Teenager”)
c. if age > 12
print(“Teenager”)
d. if age > 12:
print(“Teenager”)
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
231. Identify the error in the following code:
score = 71
if score >= 85
print("You are Eligible!")
a. No Error
b. if score => 85:
print(“You are Eligible!”)
c. if score >= 85:
print(“You are Eligible!”)
d. elif score >= 85:
print(“You are Eligible!”)
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
1 a 51 d 101 d 151 c 201 b
2 d 52 c 102 b 152 a 202 a
3 a 53 a 103 c 153 a 203 a
4 d 54 b 104 c 154 c 204 d
5 d 55 b 105 d 155 c 205 c
6 c 56 a 106 a 156 c 206 c
7 b 57 a 107 d 157 a 207 c
8 b 58 d 108 b 158 c 208 b
9 d 59 c 109 a 159 d 209 b
10 d 60 a 110 c 160 b 210 d
11 c 61 a 111 b 161 c 211 a
12 c 62 b 112 d 162 c 212 b
13 a 63 d 113 c 163 b 213 c
14 c 64 b 114 d 164 c 214 c
15 b 65 c 115 a 165 d 215 d
16 c 66 b 116 b 166 c 216 a
17 c 67 b 117 d 167 d 217 d
18 a 68 a 118 a 168 b 218 b
19 b 69 a 119 c 169 a 219 d
20 d 70 a 120 a 170 d 220 c
21 a 71 b 121 b 171 c 221 d
22 a 72 a 122 c 172 b 222 a
23 b 73 a 123 c 173 d 223 c
24 a 74 b 124 d 174 c 224 c
25 c 75 a 125 c 175 b 225 c
26 c 76 c 126 b 176 c 226 d
27 b 77 a 127 c 177 d 227 a
28 a 78 c 128 d 178 d 228 c
29 b 79 d 129 b 179 b 229 c
30 a 80 c 130 c 180 d 230 d
31 b 81 d 131 c 181 a 231 c
32 d 82 d 132 d 182 b 232 c
33 c 83 d 133 c 183 c 233 c
34 a 84 b 134 a 184 d 234 b
35 a 85 d 135 c 185 b 235 c
36 a 86 a 136 d 186 a 236 d
37 b 87 c 137 d 187 a 237 b
38 b 88 d 138 c 188 d 238 c
39 d 89 d 139 a 189 b 239 c
40 d 90 b 140 d 190 d 240 c
41 b 91 c 141 c 191 a 241 a
42 c 92 a 142 b 192 a 242 c
43 a 93 a 143 b 193 d 243 d
44 d 94 d 144 d 194 b 244 b
45 b 95 c 145 c 195 d 245 d
46 b 96 a 146 a 196 c 246 c
47 b 97 b 147 d 197 c 247 d
48 c 98 d 148 d 198 d 248 c
49 b 99 b 149 a 199 b 249 b
50 c 100 d 150 b 200 a 250 a
CHAPTER 20
Database Programming with
Python
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.
Multiple choice questions
1. Which of the following is a commonly used database management
system in Python?
a. SQLite
b. MySQL
c. PostgreSQL
d. All of the above
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
3. In Python, which module is commonly used for interacting with
databases?
a. os
b. sys
c. sqlite3
d. math
4. Which of the following commands is used to create a new database
in SQLite?
a. CREATE DATABASE
b. CREATE TABLE
c. CREATE INDEX
d. None of the above
5. In Python, which of the following methods is used to execute an
SQL query on a database connection object?
a. query() c. run()
b. execute() d. send()
6. What is the purpose of the PRIMARY KEY constraint in a
database table?
a. To specify a unique identifier for each record in the table
b. To enforce data integrity rules
c. To improve the performance of database queries
d. None of the above
7. Which of the following is an example of a relational database
management system (RDBMS)?
a. MongoDB c. Redis
b. SQLite d. Cassandra
8. How do we connect to a SQLite database in Python?
a. Using the connect() function from the sqlite3 module
b. Using the open() function from the sqlite3 module
c. Using the connect() function from the os module
d. Using the open() function from the os module
9. What is the purpose of the WHERE clause in a SQL query?
a. To specify the columns to retrieve from the table
b. To specify the order in which the results are returned
c. To filter rows based on a specific condition
d. None of the above
10. What is the purpose of the GROUP BY clause in a SQL query?
a. To group rows based on a specific column or expression
b. To filter rows based on a specific condition
c. To sort the result set in ascending order
d. None of the above
11. Which of the following statements about transactions in a
database management system is true?
a. A transaction is a unit of work that is either fully completed or
fully undone.
b. Transactions are not used in database management systems.
c. A transaction in a database management system can be partially
completed.
d. None of the above
12. In Python, which module is commonly used for connecting to a
MySQL database?
a. mysql c. pymysql
b. sqlite3 d. mongodb
13. What happens if a database table has a foreign key constraint, and
the referenced key is deleted?
a. The record with the foreign key constraint is also deleted
b. The referenced record is updated to match the new key
c. The operation is blocked to maintain data integrity
d. None of the above
14. Which of the following SQL statements is used to modify existing
records in a database table?
a. UPDATE c. INSERT
b. DELETE d. SELECT
15. How do you retrieve the number of rows affected by an SQL
query in Python?
a. Using the fetchall() method
b. Using the rowcount property of the cursor object
c. Using the execute() method
d. None of the above
16. What is the purpose of the ORDER BY clause in a SQL query?
a. To filter rows based on a specific condition
b. To group rows based on a specific column or expression
c. To sort the result set in ascending or descending order
d. None of the above
17. What is the purpose of the LIMIT clause in a SQL query?
a. To filter rows based on a specific condition
b. To group rows based on a specific column or expression
c. To limit the number of rows returned in the result set
d. None of the above
18. Which of the following is an example of a NoSQL database?
a. MySQL c. MongoDB
b. PostgreSQL d. SQLite
19. What is the purpose of the CREATE TABLE statement in SQL?
a. To delete a table from the database
b. To insert new records into a table
c. To create a new table with specified columns and properties
d. None of the above
20. How do we retrieve data from a database in Python using the
sqlite3 module?
a. Using the fetchone() method
b. Using the fetchall() method
c. Using the fetchmany() method
d. All of the above
21. What is the purpose of the DROP TABLE statement in SQL?
a. To delete a specific record from a table
b. To insert a new table into the database
c. To remove an entire table from the database
d. None of the above
22. Which of the following methods is used to commit a transaction in
Python?
a. commit()
b. save()
c. execute()
d. None of the above
23. What is the purpose of the INSERT INTO statement in SQL?
a. To update existing records in a table
b. To delete records from a table
c. To insert new records into a table
d. None of the above
24. Which of the following is an example of a database cursor in
Python?
a. select()
b. fetchone()
c. fetchall()
d. None of the above
25. What is the purpose of the JOIN clause in SQL?
a. To filter rows based on a specific condition
b. To combine data from two or more tables based on a related
column
c. To group rows based on a specific column or expression
d. None of the above
26. Which of the following statements is true about the ACID
properties of a database transaction?
a. ACID stands for Atomicity, Consistency, Integrity, Durability
b. ACID stands for Atomicity, Consistency, Isolation, Durability
c. ACID stands for Atomicity, Consistency, Isolation, Duration
d. None of the above
27. What is the purpose of the TRUNCATE TABLE statement in SQL?
a. To delete a specific record from a table
b. To insert a new table into the database
c. To remove all records from a table
d. None of the above
28. Which of the following commands creates a new database in
MySQL?
a. CREATE DATABASE
b. CREATE TABLE
c. CREATE INDEX
d. None of the above
29. What is the purpose of the DESC keyword in an SQL query?
a. To filter rows based on a specific condition
b. To sort the result set in descending order
c. To group rows based on a specific column or expression
d. None of the above
30. In a relational database table, a primary key constraint ensures
that:
a. The values in the column are unique and not null
b. The values in the column are unique but can be null
c. The values in the column are not null but can be duplicated
d. The values in the column are not unique but can be null
31. Which of the following statements about the SQLite database
engine is true?
a. SQLite is a serverless, self-contained, zero-configuration
database engine
b. SQLite is designed for large-scale enterprise applications
c. SQLite supports multiple simultaneous connections to a database
d. None of the above
32. What is the purpose of the WHERE clause in an SQL UPDATE
statement?
a. To specify the columns to update
b. To specify the values to update
c. To filter the rows to be updated
d. None of the above
33. Which of the following is an example of an aggregate function in
SQL?
a. COUNT() c. INSERT()
b. SELECT() d. UPDATE()
34. In Python, which module is commonly used for interacting with
PostgreSQL databases?
a. psycopg2
b. sqlite3
c. MySQLdb
d. No module is required
35. What is the purpose of the DISTINCT keyword in an SQL
query?
a. To filter rows based on a specific condition
b. To group rows based on a specific column or expression
c. To eliminate duplicate values in the result set
d. None of the above
36. Which of the following commands is used to create a new table in
an SQLite database?
a. CREATE TABLE
b. CREATE DATABASE
c. CREATE INDEX
d. None of the above
37. What is the purpose of the LIKE keyword in an SQL query?
a. To filter rows based on a specific condition
b. To group rows based on a specific column or expression
c. To search for patterns in a column’s values
d. None of the above
38. In a database table, what is the purpose of a foreign key
constraint?
a. To specify a unique identifier for each record in the table
b. To enforce data integrity rules between tables
c. To improve the performance of database queries
d. None of the above
39. Which of the following statements about normalization in
database design is true?
a. Normalization is the process of organizing data in a database to
minimize redundancy
b. Normalization is not an important concept in database design
c. Normalization refers to the process of denormalizing a database
d. None of the above
40. What is the purpose of the ROLLBACK statement in SQL?
a. To commit a transaction and make its changes permanent
b. To undo any changes made in a transaction
c. To retrieve data from a database
d. None of the above
41. In the SQL statement SELECT * FROM Customers WHERE
City='Berlin', what does Berlin represent?
a. Table name
b. Column name
c. Conditional expression
d. None of the above
42. How do we retrieve the last inserted ID in an SQLite database in
Python?
a. Using the lastrowid attribute of the cursor object
b. Using the fetchone() method
c. Using the fetchall() method
d. None of the above
43. Which of the following commands creates a new index in a
database table?
a. CREATE INDEX
b. CREATE TABLE
c. CREATE DATABASE
d. None of the above
44. What is the purpose of the DROP DATABASE statement in SQL?
a. To delete tables within a database
b. To delete a specific record from a table
c. To remove an entire database
d. None of the above
45. Which of the following SQL commands is used to remove a row
from a database table?
a. DROP
b. DELETE
c. TRUNCATE
d. None of the above
46. In a relational database table, a foreign key constraint is used to:
a. Ensure that a column contains unique values
b. Create an index on a column
c. Enforce a link between two tables
d. None of the above
47. What is the purpose of the HAVING clause in an SQL query?
a. To filter rows based on a specific condition
b. To group rows based on a specific column or expression
c. To filter grouped rows based on a specific condition
d. None of the above
48. Which of the following is an example of a non-relational database?
a. MongoDB c. PostgreSQL
b. MySQL d. SQLite
49. In Python, what is the purpose of the executemany() method in
the sqlite3 module?
a. To execute multiple SQL queries at once
b. To execute a single SQL query multiple times with different
parameters
c. To execute a single SQL query and return multiple result sets
d. None of the above
50. What is the purpose of the UNION operator in an SQL query?
a. To combine the results of two or more SELECT statements
b. To filter rows based on a specific condition
c. To group rows based on a specific column or expression
d. None of the above
51. Which SQL commands are used to add a new column to a
database table?
a. ALTER
b. UPDATE
c. INSERT
d. None of the above
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
53. What is the purpose of the CASCADE keyword in a foreign key
constraint in a database table?
a. To prevent updates to the referenced key
b. To delete the referencing row if the referenced row is deleted
c. To update the referencing row if the referenced row is updated
d. None of the above
54. Which of the following SQL statements is used to remove a table
from a database?
a. DROP TABLE
b. DROP DATABASE
c. DELETE TABLE
d. None of the above
55. What is the purpose of the AVG function in SQL?
a. To count the number of rows in a result set
b. To calculate the average value of a column in a result set
c. To find the maximum value in a column in a result set
d. None of the above
56. In SQL, the WHERE clause is used to:
a. Group rows based on a specific column
b. Sort rows based on a specific column
c. Filter rows based on a specific condition
d. None of the above
57. Which of the following SQL commands creates a unique
constraint on a column?
a. ALTER
b. CREATE UNIQUE
c. ADD CONSTRAINT
d. None of the above
58. What is the purpose of the EXISTS keyword in an SQL query?
a. To check if a column exists in a database table
b. To filter rows based on a specific condition
c. To determine if a subquery returns any rows
d. None of the above
59. In SQL, the GROUP BY statement is used to:
a. Filter rows based on a specific condition
b. Sort rows based on a specific column
c. Group rows based on a specific column or expression
d. None of the above
60. Which of the following SQL statements is used to update existing
records in a database table?
a. UPDATE c. INSERT
b. DELETE d. SELECT
61. What is the purpose of the TRUNCATE TABLE statement in SQL?
a. To delete a specific record from a table
b. To insert a new table into the database
c. To remove all records from a table
d. None of the above
62. What is MySQL?
a. A programming language
b. A database management system
c. A web development framework
d. A server-side scripting language
63. Which Python module is used to connect to MySQL database?
a. sqlapi c. pymysql
b. mysqlapi d. mysqldb
64. How can you execute a MySQL query in Python using pymysql
module?
a. mysql_query(“SELECT * FROM table”)
b. execute(“SELECT * FROM table”)
c. connection.execute(“SELECT * FROM table”)
d. cursor.execute(“SELECT * FROM table”)
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()
67. What does the “WHERE” clause in a MySQL query do?
a. Joins two tables
b. Specifies the order of results
c. Filters rows based on a condition
d. Groups rows based on a common value
68. Which command is used to create a new table in MySQL using
pymysql?
a. CREATE
b. ADD
c. MAKE
d. INSERT
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
71. What is the purpose of the “ORDER BY” clause in a MySQL
query?
a. Limits the number of results
b. Groups rows based on a common value
c. Sorts the results based on specified columns
d. Filters rows based on a condition
72. Which operator is used for comparison in a MySQL query?
a. != c. --
b. <> d. ==
73. How can you delete rows from a MySQL table using pymysql?
a. delete()
b. remove()
c. DROP row()
d. DELETE FROM table WHERE condition
74. Which keyword is used to specify a unique constraint in MySQL
table creation?
a. UNIQUE
b. CONSTRAINT
c. KEY
d. INDEX
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()
78. Which method is used to close a connection to a MySQL database
using pymysql?
a. close_connection()
b. disconnect()
c. close()
d. finish()
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
80. What is the purpose of the “ON DUPLICATE KEY UPDATE”
clause in a MySQL query?
a. Inserts a new row if a duplicate key is found
b. Updates existing rows if a duplicate key is found
c. Deletes rows if a duplicate key is found
d. Ignores duplicate keys
81. Which SQL function counts the number of rows in a MySQL
table?
a. COUNT() c. AVG()
b. SUM() d. MAX()
82. How can we retrieve the column names of a MySQL table using
pymysql?
a. cursor.get_columns()
b. cursor.columns()
c. cursor.description
d. cursor.get_columns_info()
83. What is the purpose of the “LIKE” operator in a MySQL query?
a. Joins two tables
b. Filters rows based on a condition
c. Matches patterns in a column value
d. Groups rows based on a common value
84. How can we rollback a transaction in MySQL using pymysql?
a. commit() c. rollback()
b. savepoint() d. undo()
85. Which method fetches a single row of a MySQL query result using
pymysql?
a. fetch_one() c. fetch_row()
b. fetch_single() d. fetch_next()
86. What is the purpose of the "HAVING” clause in a MySQL query?
a. Groups rows based on a common value
b. Filters rows based on a condition
c. Specifies the order of results
d. Limits the number of results
87. How can we define a foreign key constraint in a MySQL table
using pymysql?
a. FOREIGN KEY(column) REFERENCES table(column)
b. ADD FOREIGN KEY(column) REFERENCES table(column)
c. CREATE FOREIGN KEY(column) REFERENCES
table(column)
d. LINK FOREIGN KEY(column) REFERENCES table(column)
88. Which SQL function is used to find the maximum value in a
column in MySQL?
a. COUNT() c. AVG()
b. SUM() d. MAX()
89. How can we handle NULL values in a MySQL query using
pymysql?
a. ISNULL() c. COALESCE()
b. NULLIF() d. IFNULL()
90. What is the purpose of the “GROUP BY” clause in a MySQL
query?
a. Filters rows based on a condition
b. Sorts the results based on specified columns
c. Limits the number of results
d. Groups rows based on a common value
91. How can you insert multiple rows into a MySQL table using
pymysql?
a. insert_many()
b. add_rows()
c. executemany()
d. batch_insert()
92. Which Python library is used to interact with MySQL databases?
a. psycopg2 c. pymysql
b. sqlalchemy d. sqlite3
93. What is the purpose of the “AS” keyword in a MySQL query?
a. To alias a column or table
b. To combine two columns
c. To apply an aggregate function
d. To filter rows based on a condition
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()
95. What is the default character encoding for MySQL connections in
Python using pymysql?
a. ASCII c. Latin1
b. UTF-8 d. Unicode
96. How can we limit the number of rows a MySQL query returns
using pymysql?
a. LIMIT n c. ROWS n
b. TOP n d. FETCH n
97. What is the purpose of the “JOIN” clause in a MySQL query?
a. Limits the number of results
b. Filters rows based on a condition
c. Combines rows from two tables
d. Groups rows based on a common value
98. How can we retrieve the database server version using pymysql?
a. cursor.server_version
b. server_version()
c. SELECT @@VERSION
d. GET version()
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’
101. What is the purpose of the “IN” operator in a MySQL query?
a. Matches values in a column with a list of specified values
b. Filters rows based on a condition
c. Groups rows based on a common value
d. Limits the number of results
102. How can you grant privileges to a user in MySQL using
pymysql?
a. GRANT ALL PRIVILEGES ON database.table TO
‘username’@’hostname’
b. GIVE ALL PRIVILEGES TO ‘username’@’hostname’ ON
database.table
c. ALLOW ALL PRIVILEGES ON table FOR
‘username’@’hostname’
d. PRIVILEGE ALL TO ‘username’@’hostname’ ON
database.table
103. What is the purpose of the “DROP” command in MySQL?
a. Deletes a database
b. Deletes a table
c. Deletes a row
d. Deletes a column
104. How can we retrieve the number of columns in a MySQL query
result using pymysql?
a. cursor.col_count()
b. cursor.column_count
c. cursor.description
d. cursor.get_columns_count()
105. What is the purpose of the “LIKE %value%” syntax in a
MySQL query?
a. Matches exact values in a column
b. Matches any value in a column
c. Matches values starting with “value”
d. Matches values containing “value”
106. How can we delete a MySQL database using pymysql?
a. DELETE DATABASE database_name
b. DROP DATABASE database_name
c. REMOVE DATABASE database_name
d. ERASE DATABASE database_name
107. Which SQL function is used to find the minimum value in a
column in MySQL?
a. COUNT()
b. SUM()
c. AVG()
d. MIN()
108. How can we check if a table exists in a MySQL database using
pymysql?
a. SELECT table_name FROM information_schema.tables
WHERE table_name = ‘table’
b. CHECK TABLE ‘table’
c. DESCRIBE ‘table’
d. SHOW TABLES LIKE ‘table’
109. What is the purpose of the “NULL” keyword in MySQL?
a. Represents an empty string
b. Represents a zero-value
c. Represents a missing or unknown value
d. Represents a wildcard value
110. How can we create an index on a column in a MySQL table using
pymysql?
a. CREATE INDEX idx_name ON table(column)
b. INDEX table(column) AS idx_name
c. ADD INDEX column ON table
d. ADD idx_name TO INDEX ON table(column)
111. What does the “DISTINCT” keyword do in a MySQL query?
a. Groups rows based on a common value
b. Sorts the results based on specified columns
c. Filters duplicate rows from the result set
d. Limits the number of results
112. What is the primary library used to connect Python with an SQL
database?
a. SQLAlchemy
b. psycopg2
c. pyodbc
d. pandas
113. Which of the following methods is used to establish a connection to
an SQL database in Python?
a. create_connection()
b. connect()
c. open_connection()
d. establish_connection()
114. Which of the following statements is used to execute a Python SQL
query on a database?
a. db.query()
b. cursor.execute()
c. run_query()
d. fetch_query()
115. What is the purpose of a cursor in Python when working with an
SQL database?
a. To fetch data from the database
b. To execute SQL queries
c. To establish a connection to the database
d. To create a new database
116. Which of the following methods is used to retrieve data from an
SQL query in Python?
a. cursor.retrieve()
b. fetchall()
c. fetch_query()
d. execute_query()
117. What is the purpose of a connection pool in Python when
connecting to an SQL database?
a. It allows multiple simultaneous connections to the database
b. It speeds up the execution of SQL queries
c. It reduces the risk of data corruption
d. It is not necessary when using Python with an SQL database
118. Which of the following is NOT a commonly used SQL database
with Python?
a. MySQL c. MongoDB
b. SQLite d. PostgreSQL
119. How can we securely pass parameters to an SQL query in Python
to prevent SQL injection attacks?
a. Sanitize input before passing it to the query
b. Use prepared statements
c. Use stored procedures
d. All of the above
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
121. How can you check if a connection to an SQL database was
successfully established in Python?
a. Check if the cursor is open
b. Check if the connection object is None
c. Catch any exceptions thrown during the connection process
d. All of the above
122. Which of the following Python libraries is specifically designed for
working with PostgreSQL databases?
a. pyodbc c. psycopg2
b. SQLAlchemy d. pymysql
123. How can we close a connection to an SQL database in Python?
a. connection.close()
b. cursor.close()
c. Both A and B
d. Neither A nor B
124. When using the SQLAlchemy library in Python, what is an
ORM?
a. Object-Relational Mapping
b. Object-Resource Mapping
c. Object-Routing Mapping
d. Object-Remote Mapping
125. We need to install a separate driver in Python for each SQL
database you want to connect to.
a. True b. False
126. What is the primary advantage of using stored procedures when
connecting Python to an SQL database?
a. Improved performance
b. Increased security
c. Simplified code execution
d. All of the above
127. Which of the following is a popular database management system
for Python applications?
a. MySQL
b. PostgreSQL
c. Microsoft SQL Server
d. All of the above
128. In Python, which library is commonly used to interact with a
MySQL database?
a. pyodbc
b. psycopg2
c. pymysql
d. SQLAlchemy
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
130. What method is used to commit changes to an SQL database in
Python?
a. commit()
b. save()
c. update()
d. execute()
131. How can we handle errors when executing an SQL query in
Python?
a. Use a try-except block
b. Check for errors using an if statement
c. Use a finally block
d. All of the above
132. Which of the following is NOT a step in connecting Python with an
SQL database?
a. Importing the appropriate libraries
b. Establishing a connection
c. Writing and executing SQL queries
d. Creating a GUI interface
133. What is the primary purpose of a database schema in an SQL
database?
a. To store data
b. To manage database security
c. To define the structure and organization of the database
d. To optimize database performance
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
135. Which of the following is an open-source SQL database commonly
used with Python?
a. Oracle Database
b. Microsoft SQL Server
c. SQLite
d. IBM Db2
136. We can connect to an SQL database in Python without providing a
username and password.
a. True
b. False
137. How can we handle long-running SQL queries in Python to
prevent the connection from timing out?
a. Increase the timeout limit in the connection string
b. Use a context manager to automatically close the connection
c. Implement a progress bar to monitor query progress
d. Use asynchronous programming techniques
138. In which of the following scenarios would you use a database
cursor when working with an SQL database in Python?
a. Reading data from the database
b. Writing data to the database
c. Executing SQL queries
d. All of the above
139. What is the purpose of a transaction in an SQL database when
working with Python?
a. To ensure data integrity
b. To prevent concurrent access to the database
c. To improve performance
d. All of the above
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())
141. Which of the following is a common method for securing an SQL
database connection in Python?
a. Storing database credentials in plaintext files
b. Hardcoding credentials in the script
c. Using environment variables to store credentials
d. Passing credentials as command-line arguments
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
143. What is the primary function of the commit() method when
working with an SQL database in Python?
a. To undo any changes made to the database
b. To save changes made during a transaction
c. To close the database connection
d. To roll back a transaction
144. How can you optimize the performance of an SQL query in
Python by indexing columns in a database table?
a. Use the CREATE INDEX statement in SQL
b. Use the fetchone() method
c. Use the optimize() method
d. Use the GROUP BY clause in the SQL query
145. Which of the following is NOT an advantage of using an ORM
when connecting Python with an SQL database?
a. Simplified code structure
b. Improved data integrity
c. Automatic mapping of Python objects to database tables
d. Increased database performance
146. How can you rollback a transaction in Python if an error occurs
during the execution of an SQL query?
a. Use the rollback() method
b. Use the undo() method
c. Use the cancel() method
d. Use the execute() method with a rollback flag
147. What is the purpose of the autocommit feature in an SQL
database when working with Python?
a. To automatically commit changes after each transaction
b. To roll back changes after each transaction
c. To prevent changes from being committed
d. To increase database security
148. Which is a common practice for optimizing database performance
when connecting Python with an SQL database?
a. Using stored procedures
b. Indexing frequently queried columns
c. Normalizing database tables
d. All of the above
149. How can you handle database errors in Python to provide
meaningful error messages to the user?
a. Use the raise keyword to raise custom exceptions
b. Use the print statement to display errors
c. Use the logger module to log errors
d. All of the above
150. What is the primary purpose of using connection pooling in
Python to manage database connections?
a. To reduce the number of open connections to the database
b. To increase database performance
c. To improve data integrity
d. To prevent SQL injection attacks
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
152. Which of the following methods can be used to pass parameters to
an SQL query in Python using the psycopg2 library?
a. Use string interpolation
b. Use query placeholders
c. Concatenate strings
d. Use the %s syntax
153. In Python, which method is commonly used to create a new
database table in an SQL database?
a. create_table()
b. table.create()
c. cursor.execute()
d. db.execute()
154. How can you manage database transactions in Python to ensure
data integrity when working with an SQL database?
a. Use a try-except block to handle errors
b. Use the commit() and rollback() methods
c. Implement a logging mechanism
d. All of the above
155. In Python, you can connect to an SQL database using a connection
string.
a. True b. False
156. Which of the following is a common exception that may occur
when connecting Python with an SQL database?
a. OSError
b. SyntaxError
c. DatabaseError
d. ValueError
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
158. What is the purpose of a database driver when connecting Python
with an SQL database?
a. To manage database connections
b. To translate Python code to SQL statements
c. To provide a consistent API for interacting with different
databases
d. All of the above
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
161. What is the primary benefit of using an ORM when connecting
Python with an SQL database?
a. Simplified database interactions
b. Better query performance
c. Enhanced data security
d. All of the above
162. What is SQLite?
a. A programming language
b. A relational database management system
c. A web scraping tool
d. A cloud storage service
163. Which module is used to work with SQLite in Python?
a. sqlite3
b. pandas
c. requests
d. datetime
164. What is the command to create a new SQLite database in Python?
a. CREATE DATABASE
b. CREATE TABLE
c. CONNECT DATABASE
d. None of the above
165. How can you establish a connection to an SQLite database in
Python?
a. sqlite3.create_connection(“database.db”)
b. sqlite3.connect(“database.db”)
c. sqlite3.open_connection(“database.db”)
d. sqlite3.connection(“database.db”)
166. Which SQL command is used to create a table in an SQLite
database?
a. CREATE TABLE
b. ADD TABLE
c. NEW TABLE
d. INSERT INTO TABLE
167. What does the following SQL statement do?
"INSERT INTO users (name, age) VALUES (‘John’,
25)"
a. Inserts a new column into the users table
b. Inserts a new row into the users table
c. Drops the users table
d. Updates the users table
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”)
169. What is the purpose of the following Python code snippet?
"cursor.execute("SELECT * FROM users WHERE age
> 30")"
a. Fetches all rows from the users table
b. Inserts a new row into the users table
c. Updates the age column of the users table
d. Fetches rows from the users table where the age column is greater
than 30
170. Which of the following is not a valid SQLite data type?
a. INTEGER
b. FLOAT
c. STRING
d. BLOB
171. How do you delete a table from an SQLite database in Python?
a. DELETE TABLE users
b. DROP TABLE users
c. REMOVE TABLE users
d. CLEAR TABLE users
172. What is the purpose of the following Python code snippet?
"cursor.execute("DELETE FROM users WHERE age <
18")"
a. Adds a new row to the users table
b. Updates the users table
c. Deletes rows from the users table where the age is less than 18
d. Fetches all rows from the users table
173. How do you update a row in an SQLite table using Python?
a. cursor.execute(“UPDATE users SET age=30 WHERE
name=’John’”)
b. cursor.update_row(“users”, “John”, 30)
c. cursor.update(“users”, “age”, 30)
d. connection.query(“UPDATE users SET age=30 WHERE
name=’John’”)
174. What is the purpose of the following Python code snippet?
"cursor.execute("SELECT COUNT(*) FROM users")"
a. Retrieves the number of rows in the users table
b. Adds a new row to the users table
c. Deletes all rows from the users table
d. Updates the users table
175. How do you commit changes to an SQLite database in Python?
a. cursor.commit()
b. connection.commit()
c. connection.save()
d. cursor.save()
176. What is the purpose of the following Python code snippet?
"cursor.execute("PRAGMA table_info(users)")"
a. Fetches all rows from the users table
b. Inserts a new row into the users table
c. Retrieves information about the columns in the users table
d. Updates the users 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
178. What is the purpose of the following Python code snippet?
"connection.close()"
a. Opens a new connection to the database
b. Closes the connection to the database
c. Commits changes to the database
d. Fetches rows from the database
179. How do you use Python to create an index on a column in an
SQLite table?
a. cursor.create_index(“users”, “name”)
b. cursor.execute(“CREATE INDEX idx_name ON users (name)”)
c. connection.create_index(“users”, “name”)
d. connection.execute(“CREATE INDEX idx_name ON users
(name)”)
180. What is the purpose of the following Python code snippet?
"cursor.execute("PRAGMA foreign_keys = ON")"
a. Turns on foreign key constraints for the database
b. Turns off foreign key constraints for the database
c. Adds a new foreign key constraint to a table
d. Fetches information about foreign key constraints
181. How do you implement transactions in an SQLite database using
Python?
a. Use the commit() method
b. Use the rollback() method
c. Use the begin_transaction() method
d. Use the transaction() context manager
182. What is the purpose of the following Python code snippet?
"cursor.execute("SELECT * FROM users ORDER BY
name DESC")"
a. Fetches all rows from the users table
b. Inserts a new row into the users table
c. Updates the users table
d. Fetches rows from the users table in descending order of the
name column
183. How do you create a view in an SQLite database using Python?
a. cursor.add_view(“users_view”, “SELECT * FROM users”)
b. cursor.execute(“CREATE VIEW users_view AS SELECT *
FROM users”)
c. connection.create_view(“users_view”, “SELECT * FROM
users”)
d. connection.execute(“CREATE VIEW users_view AS SELECT *
FROM users”)
184. What is the purpose of the following Python code snippet?
"cursor.execute("SELECT * FROM users LIMIT 5")"
a. Fetches all rows from the users table
b. Fetches the first 5 rows from the users table
c. Inserts a new row into the users table
d. Updates the users table
185. How do you retrieve metadata about a SQLite table in Python?
a. Use the PRAGMA table_info() statement
b. Use the SHOW TABLE command
c. Use the DESCRIBE TABLE statement
d. Use the FETCH TABLE command
186. What is the purpose of the following Python code snippet?
"cursor.execute("DROP INDEX idx_name")"
a. Creates a new index on the name column
b. Deletes the existing index on the name column
c. Drops the name column from the table
d. Updates the index on the name column
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
188. What is the purpose of the following Python code snippet?
"cursor.execute("SELECT * FROM users WHERE name
LIKE 'J%'")"
a. Fetches all rows from the users table
b. Updates the users table
c. Fetches rows from the users table where the name starts with the
letter ‘J’
d. Inserts a new row into the users table
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
190. What is the purpose of the following Python code snippet?
"cursor.execute("ATTACH DATABASE 'other.db' AS
other")"
a. Attaches the ‘other.db’ database to the current database
b. Detaches the ‘other.db’ database from the current database
c. Creates a new database named ‘other’
d. Updates the ‘other.db’ database
191. How do you retrieve the schema of an SQLite database in Python?
a. Use the PRAGMA schema_info() statement
b. Use the SHOW TABLES command
c. Use the schema() method
d. Use the PRAGMA table_list() statement
192. What is the purpose of the following Python code snippet?
"cursor.execute("DROP DATABASE users")"
a. Deletes the users table
b. Deletes the users database
c. Deletes the users schema
d. Deletes all rows from the users table
193. How do you retrieve the size of an SQLite database in Python?
a. Use the PRAGMA database_size() statement
b. Use the SHOW SIZE command
c. Use the size() method
d. Use the PRAGMA database_list() statement
194. What is the purpose of the following Python code snippet?
"cursor.execute("ALTER TABLE users ADD COLUMN
email VARCHAR(50)")"
a. Adds a new email column to the users table
b. Updates the users table
c. Deletes the users table
d. Inserts a new row into the users table
195. How do you check if a table exists in an SQLite database in
Python?
a. Use the EXISTS TABLE statement
b. Use the PRAGMA table_info() statement
c. Use the SHOW TABLES command
d. Use the IF EXISTS clause
196. What is the purpose of the following Python code snippet?
"cursor.execute("CREATE INDEX IF NOT EXISTS
idx_name ON users (name)")"
a. Creates a new index on the name column if it does not exist
b. Updates the existing index on the name column
c. Deletes the existing index on the name column
d. Fetches rows from the users table
197. How do you retrieve the list of tables in an SQLite database in
Python?
a. Use the PRAGMA table_info() statement
b. Use the SHOW TABLES command
c. Use the tables() method
d. Use the PRAGMA table_list() statement
198. What is the purpose of the following Python code snippet?
“cursor.execute(“UPDATE users SET age=age+1”)”
a. Updates the age column in the users table
b. Fetches all rows from the users table
c. Inserts a new row into the users table
d. Drops the users table
199. How do you retrieve the list of columns in an SQLite table in
Python?
a. Use the PRAGMA column_info() statement
b. Use the SHOW COLUMNS command
c. Use the columns() method
d. Use the PRAGMA table_info() statement
200. What is the purpose of the following Python code snippet?
“cursor.execute(“SELECT * FROM users INNER JOIN addresses ON
users.id = addresses.user_id”)”
a. Fetches all rows from the users and addresses tables
b. Inserts a new row into the addresses table
c. Updates the users and addresses tables
d. Deletes a row from the users table
201. How do you retrieve the SQLite version using Python?
a. Use the PRAGMA version() statement
b. Use the SHOW VERSION command
c. Use the version() method
d. Use the PRAGMA database_list() statement
202. What is the purpose of the following Python code snippet?
“cursor.execute(“ALTER TABLE users RENAME TO customers”)”
a. Renames the users table to customers
b. Adds a new customers table
c. Updates the users table
d. Drops the users table
203. How do you retrieve the list of indices in an SQLite database in
Python?
a. Use the PRAGMA index_list() statement
b. Use the SHOW INDEXES command
c. Use the indices() method
d. Use the PRAGMA index_info() statement
204. What is the purpose of the following Python code snippet?
“cursor.execute(“CREATE TRIGGER before_insert_users BEFORE
INSERT ON users BEGIN PRINT(‘Before insert’) END”)”
a. Creates a new trigger on the before_insert_users event
b. Updates the users table
c. Inserts a new row into the users table
d. Drops the users table
205. How do you retrieve the list of triggers in an SQLite database in
Python?
a. Use the PRAGMA triggers() statement
b. Use the SHOW TRIGGERS command
c. Use the triggers() method
d. Use the PRAGMA trigger_info() statement
206. What is the purpose of the following Python code snippet?
“cursor.execute(“BEGIN TRANSACTION”)”
a. Begins a new transaction
b. Ends the current transaction
c. Inserts a new row into the users table
d. Updates the users table
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
208. What is the purpose of the following Python code snippet?
“cursor.execute(“CREATE VIEW users_view AS
SELECT * FROM users”)”
a. Creates a new view named users_view
b. Updates the users table
c. Inserts a new row into the users table
d. Drops the users table
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
210. What is the purpose of the following Python code snippet?
“cursor.execute(“DROP VIEW users_view”)”
a. Deletes the users_view view
b. Deletes the users_view table
c. Deletes the users_view schema
d. Deletes all rows from the users_view table
211. How do you retrieve the list of views in an SQLite database in
Python?
a. Use the PRAGMA view_list() statement
b. Use the SHOW VIEWS command
c. Use the views() method
d. Use the PRAGMA table_list() statement
212. What is MongoDB?
a. A relational database management system
b. A document-oriented database program
c. A programming language
d. A web development framework
213. Which of the following is not a valid data type in MongoDB?
a. string
b. date
c. int
d. float
214. How do you connect to a MongoDB database in Python?
a. Using the pymongo library
b. Using the pymysql library
c. Using the mongoengine library
d. Using the django library
215. Which of the following is true about ObjectId in MongoDB?
a. It is a unique identifier for a document in a collection
b. It is automatically generated by MongoDB when a document is
inserted
c. It is a hexadecimal string of 24 characters
d. All of the above
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
217. How can you query documents in a MongoDB collection using
Python?
a. Using the find() method
b. Using the search() method
c. Using the query() method
d. Using the select() method
218. What is aggregation in MongoDB?
a. Combining multiple collections into one
b. Grouping and processing data in a collection
c. Creating indexes on a collection
d. None of the above
219. Which of the following is not an aggregation pipeline stage in
MongoDB?
a. group c. match
b. sort d. select
220. How can you update a document in a MongoDB collection using
Python?
a. Using the update() method
b. Using the modify() method
c. Using the patch() method
d. Using the update_one() method
221. What is the purpose of indexing in MongoDB?
a. To make data retrieval faster
b. To create relationships between collections
c. To compress data in a collection
d. None of the above
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
223. What is GridFS in MongoDB?
a. A filesystem in mongodb for storing large files
b. A data structure used for indexing documents
c. A mechanism for encrypting data in a collection
d. None of the above
224. How can you use Python to create an index on a field in a
MongoDB collection?
a. Using the index_one() method
b. Using the create_index() method
c. Using the add_index() method
d. Using the set_index() method
225. What is sharding in MongoDB?
a. A way to distribute data across multiple servers
b. A way to group data in a collection
c. A way to sort data in a collection
d. None of the above
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
227. What is a replica set in MongoDB?
a. A way to combine multiple collections
b. A group of mongodb instances that store the same data
c. A way to compress data in a collection
d. None of the above
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
229. What is the purpose of the $lookup operator in MongoDB?
a. To join data from multiple collections
b. To filter data in a collection
c. To group data in a collection
d. None of the above
230. How can you create a capped collection in MongoDB using
Python?
a. Using the create_capped_collection() method
b. Using the capped() method
c. Using the capped_collection() method
d. Using the create_collection() method with the capped option
231. What is the default port number for MongoDB?
a. 27017
b. 3306
c. 5432
d. 1521
232. How can you limit the number of documents returned in a
MongoDB query result using Python?
a. Using the limit() method
b. Using the set_limit() method
c. Using the filter() method
d. Using the get_limit() method
233. What is the purpose of the $unwind operator in MongoDB?
a. To flatten arrays in a document
b. To group data in a collection
c. To filter arrays in a document
d. None of the above
234. How can you perform a partial text search in a MongoDB
collection using Python?
a. Using the find() method with a partial text search query
b. Using the search() method with a partial text search query
c. Using the partial_text() method
d. Using the partial_search() method
235. What is the purpose of the $graphLookup operator in
MongoDB?
a. To perform a graph search on data in a collection
b. To create a graph structure from data in a collection
c. To group data in a collection
d. None of the above
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
237. What is the purpose of the $geoNear operator in MongoDB?
a. To perform a geospatial search on data in a collection
b. To group data in a collection based on proximity
c. To filter data based on location
d. None of the above
238. How can you use Python to create a compound index on multiple
fields in a MongoDB collection?
a. Using the create_index() method with multiple fields
b. Using the compound_index() method
c. Using the index() method with multiple fields
d. Using the set_index() method
239. What is the purpose of the $facet operator in MongoDB?
a. To group and process data in a collection
b. To create a facet index on a field
c. To sort data in a collection
d. None of the above
240. How can you perform a full-text search in a MongoDB collection
using Python?
a. Using the full_text_search() method
b. Using the search() method with $text operator
c. Using the find_text() method
d. Using the text_search() method
241. What is the purpose of the $redact operator in MongoDB?
a. To redact sensitive information from query results
b. To group and process data in a collection
c. To filter data in a collection
d. None of the above
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
243. What is the purpose of the $map operator in MongoDB?
a. To apply an expression to each element in an array
b. To group data in a collection
c. To filter arrays in a document
d. None of the above
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
245. What is the purpose of the $out operator in MongoDB?
a. To output aggregated data to a new collection
b. To group and process data in a collection
c. To sort data in a collection
d. None of the above
246. How can you use Python to create a 2d index on a field in a
MongoDB collection?
a. Using the create_2d_index() method
b. Using the 2d_index() method
c. Using the create_index() method with the 2d option
d. Using the set_2d_index() method
247. What is the purpose of the $mod operator in MongoDB?
a. To perform modular arithmetic on values in a collection
b. To group and process data in a collection
c. To filter data based on a modulo operation
d. None of the above
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
249. What is the purpose of the $bucket operator in MongoDB?
a. To group data into buckets based on a specified expression
b. To group and process data in a collection
c. To filter data in a collection
d. None of the above
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.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Answers
Q. Answer Q. Answer Q. Answer Q. Answer Q. Answer
No No No No No
1 d 51 a 101 a 151 d 201 a
2 c 52 c 102 a 152 b 202 a
3 c 53 b 103 a 153 c 203 a
4 d 54 a 104 b 154 b 204 a
5 b 55 b 105 d 155 a 205 a
6 a 56 c 106 b 156 c 206 a
7 b 57 c 107 d 157 b 207 a
8 a 58 c 108 d 158 d 208 a
9 c 59 c 109 c 159 a 209 a
10 a 60 a 110 a 160 a 210 a
11 a 61 c 111 c 161 a 211 a
12 c 62 b 112 b 162 b 212 b
13 c 63 c 113 b 163 a 213 d
14 a 64 d 114 b 164 d 214 a
15 b 65 b 115 b 165 b 215 d
16 c 66 c 116 b 166 a 216 a
17 c 67 c 117 a 167 b 217 a
18 c 68 a 118 c 168 b 218 b
19 c 69 b 119 d 169 d 219 d
20 d 70 d 120 c 170 c 220 d
21 c 71 c 121 d 171 b 221 a
22 a 72 b 122 c 172 c 222 a
23 c 73 d 123 c 173 a 223 a
24 b 74 a 124 a 174 a 224 b
25 b 75 a 125 b 175 b 225 a
26 b 76 a 126 d 176 c 226 a
27 c 77 a 127 d 177 a 227 b
28 a 78 c 128 c 178 b 228 d
29 b 79 a 129 b 179 b 229 a
30 a 80 b 130 a 180 a 230 d
31 a 81 a 131 d 181 d 231 a
32 c 82 c 132 d 182 d 232 a
33 a 83 c 133 c 183 b 233 a
34 a 84 c 134 a 184 b 234 a
35 c 85 a 135 c 185 a 235 a
36 a 86 a 136 b 186 b 236 c
37 c 87 b 137 a 187 c 237 a
38 b 88 d 138 d 188 c 238 a
39 a 89 d 139 a 189 a 239 a
40 b 90 d 140 a 190 a 240 b
41 c 91 c 141 c 191 d 241 a
42 a 92 c 142 a 192 b 242 c
43 a 93 a 143 b 193 a 243 a
44 c 94 a 144 a 194 a 244 c
45 b 95 b 145 d 195 c 245 a
46 c 96 a 146 a 196 a 246 c
47 c 97 c 147 a 197 d 247 a
48 a 98 a 148 d 198 a 248 c
49 b 99 c 149 d 199 d 249 a
50 a 100 a 150 a 200 a 250 c