Best Selling Book Python Mastery: 350 Questions to Sharpen Your Skills First Chapter Free

Get this book FREE this week

US https://www.amazon.com/dp/B0D2Z1RSNZ

Can https://www.amazon.ca/dp/B0D2Z1RSNZ

“Python Mastery: 350 Questions to Sharpen Your Skills” is an essential resource for both novice and experienced Python programmers aiming to deepen their understanding of the language through a dynamic learning method. Authored by Laurence Svekis, a seasoned developer and educator, this book offers a robust platform for readers to test and expand their Python skills.

The book is designed around a powerful question-and-answer format that covers a wide range of Python topics. From basic syntax and built-in data types to more advanced concepts such as object-oriented programming and file handling, the questions are structured to progressively build the reader’s Python abilities. Each question is carefully crafted to challenge the reader, while detailed explanations provide deeper insights into Python’s functionalities and best practices.How to Use This Book:

Step-by-Step Learning:

  • Foundational to Advanced Topics: Begin with straightforward questions on Python basics and gradually progress to tackling complex coding problems that require thoughtful solutions and advanced programming techniques.
  • Section Reviews: At the end of each section, revisit key concepts through review questions that reinforce learning and ensure retention of important programming constructs.

Active Engagement:

  • Interactive Q&A Format: Engage with each question actively, attempting to solve it before reviewing the answer and explanation. This active learning approach helps solidify understanding and encourages critical thinking.
  • Code Implementation: After understanding the theory behind each answer, readers are encouraged to write their own code snippets or modify existing examples to better grasp the practical application of concepts.

Practical Application:

  • Real-World Problems: Apply Python to solve real-world problems presented in the book, enhancing problem-solving skills and preparing for technical job interviews where such questions are commonplace.
  • Project-Based Learning: Use the questions as a basis for small projects or components of larger projects, integrating various Python features and modules.

Community Interaction:

  • Study Groups: Join or form study groups to discuss each question’s concepts and answers, fostering a deeper understanding and sharing different perspectives on Python programming.
  • Online Forums: Participate in online forums and social media groups dedicated to Python to discuss questions from the book, share insights, and learn from a broader community.

For Educators and Trainers:

  • Teaching Resource: Educators can use this book as a curriculum tool to teach Python programming, adapting its content for lectures, exams, and practical coding assignments.
  • Continuous Learning: Use the structured format of the book to introduce new concepts or reinforce existing knowledge through regular, incremental challenges.

Conclusion:

“Python Mastery: 350 Questions to Sharpen Your Skills” is more than just a textbook; it’s a comprehensive guide to becoming proficient in Python. It invites readers to actively engage with the material, apply what they learn in practical settings, and become part of a community that values continuous improvement in coding skills. Whether preparing for a job interview, teaching a class, or simply looking to improve your coding acumen, this book is an invaluable tool in your learning journey.

Introduction to Python Questions

“Python Mastery: 350 Questions to Sharpen Your Skills” is an invaluable resource designed to help both beginners and seasoned programmers deepen their understanding of Python programming. This book offers a comprehensive collection of 350 questions, each followed by detailed explanations, making it an ideal tool for learners seeking to enhance their programming acumen, prepare for interviews, or simply test their knowledge of Python. A comprehensive overview of fundamental Python programming concepts through a Q&A format, effectively aiding in the preparation for programming interviews or exams. Here’s a summary of the topics covered throughout the document:

Data Types and Structures:

  • Basic data types: integers, floats, strings, booleans
  • Collection types: lists, tuples, sets, dictionaries
  • Immutability vs mutability: Understanding the difference between data types that can be modified after creation (lists, dictionaries) and those that cannot (tuples, strings)
  • Operations on data structures: Indexing, slicing, adding elements, removing elements, sorting, searching

Control Flow:

  • Conditional statements: if, elif, else
  • Loops: for and while loops, nested loops, loop control statements (break, continue)
  • List comprehensions: Creating new lists concisely based on existing iterables
  • Generator expressions: Generating sequences of values efficiently

Functions:

  • Defining functions: Using the def keyword, parameters, default arguments
  • Returning values: Using the return statement
  • Variable scope: Understanding local, global, and nonlocal variables
  • Lambda functions: Anonymous functions for short, single-expression tasks
  • *args and **kwargs: Handling variable-length argument lists

Classes and Objects:

  • Defining classes: Using the class keyword, constructors (__init__), methods, attributes
  • Inheritance: Creating subclasses, using super()
  • Special methods: __str__, __repr__, and others
  • Static and class methods: Understanding their differences and use cases

Modules and Packages:

  • Importing modules: Using the import statement, importing specific functions or attributes
  • Standard library modules: os, sys, datetime, random, json, re, and others

Exception Handling:

  • try and except blocks: Catching and handling exceptions
  • finally block: Executing cleanup code regardless of exceptions
  • Raising exceptions: Using the raise statement

Additional Topics:

  • File I/O: Opening, reading, writing, and closing files
  • Regular expressions: Using the re module for pattern matching
  • Working with dates and times: Using the datetime module
  • Concurrency: Brief mention of threads and locks

The book’s strength lies in its clear explanations and practical examples, which help solidify understanding. While it primarily focuses on the core aspects of Python, it also touches on some advanced concepts and modules, providing a solid foundation for further learning.

The world of programming can often feel like a complex puzzle, with each language presenting its unique set of challenges and intricacies. For those venturing into the realm of Python, “Python Questions Book” serves as a valuable guide, leading aspiring programmers through the foundational concepts and illuminating the path towards mastering this versatile language.

This book, structured as a series of questions and answers, adopts a pedagogical approach that encourages active learning and critical thinking. It delves into the core building blocks of Python, progressively building upon them to tackle more complex constructs and functionalities. Each question acts as a stepping stone, prompting the reader to engage with the material and solidify their understanding before moving forward.

Building a Strong Foundation: Data Types and Structures

The journey begins with an exploration of Python’s fundamental data types: the integers, floats, strings, and booleans that form the basic units of information. The book meticulously explains the characteristics of each type and how they interact with each other, laying the groundwork for manipulating data effectively.

Building upon this foundation, the book then delves into the realm of collection types:

  • Lists: Ordered and mutable sequences that serve as versatile containers for storing diverse data. The book delves into techniques for accessing, modifying, and manipulating lists, including slicing, indexing, and methods like append and insert.
  • Tuples: Similar to lists but immutable, providing a way to group data that should not be altered. The book clarifies the use cases for tuples and the operations that can be performed on them.
  • Sets: Unordered collections of unique elements, ideal for tasks like removing duplicates and performing set operations like union and intersection. The book illustrates how sets can be utilized for various data manipulation scenarios.
  • Dictionaries: Unordered collections that store data as key-value pairs, allowing for efficient retrieval and manipulation based on specific keys. The book explores the creation, access, and modification of dictionaries, highlighting their utility in real-world applications.

Understanding these data structures is crucial for organizing and managing data effectively in Python. The book emphasizes the importance of choosing the appropriate data structure based on the specific needs of a program, ensuring efficiency and clarity.

Controlling the Flow: Conditional Statements and Loops

With a grasp of data types and structures, the book then navigates the flow of logic within a Python program. Conditional statements, like if, elif, and else, empower programmers to make decisions based on various conditions, guiding the program’s execution down different paths. The book illustrates how to construct these statements to control the program flow effectively.

Loops, the workhorses of repetition, allow for automating tasks and iterating over data structures. The book explores the two primary loop types:

  • for loops: Designed for iterating over a sequence of elements, such as items in a list or characters in a string. The book demonstrates how to use for loops to access and process each element, often in conjunction with range functions to control the iteration count.
  • while loops: Execute repeatedly as long as a specified condition remains true. The book showcases the application of while loops for scenarios where the number of iterations is not predetermined.

To further refine control flow, the book introduces loop control statements like break and continue, which allow for exiting loops prematurely or skipping certain iterations based on specific conditions.

Abstraction and Reusability: The Power of Functions

As programs grow in complexity, the need for organization and reusability becomes paramount. Functions provide a powerful mechanism for encapsulating reusable blocks of code, promoting modularity and readability. The book delves into the art of defining functions using the def keyword, specifying parameters, and returning values using the return statement.

The concept of variable scope is explored in detail, highlighting the difference between local variables that exist only within a function and global variables accessible throughout the program. The book introduces the global and nonlocal keywords, which allow for modifying variables outside the immediate scope of a function.

For concise, single-expression functions, the book introduces lambda functions, providing a shorthand notation for defining and using simple functions on the fly.

To accommodate varying numbers of arguments, the book explores the use of *args and **kwargs, which enable functions to accept arbitrary positional and keyword arguments, respectively.

Building Blueprints: Classes and Object-Oriented Programming

Beyond functions, the book delves into the realm of object-oriented programming (OOP) and the use of classes to define blueprints for creating objects. The concept of classes is explained as a way to group data (attributes) and behavior (methods) into a single entity, promoting code organization and reusability.

The book covers the intricacies of defining classes using the class keyword, initializing objects with constructors (__init__), and defining methods that operate on the object’s attributes.

Inheritance, a fundamental principle of OOP, allows for creating new classes (subclasses) that inherit attributes and methods from existing classes (base classes). The book illustrates how inheritance can be used to build upon existing functionality and establish relationships between different types of objects.

Special methods, like __str__ and __repr__, are introduced as a way to customize the string representation of objects and provide informative output when interacting with them.

To further enhance flexibility, the book explores static and class methods, which operate on the class itself rather than individual instances, providing a way to define utility functions and factory methods.

How to Use This Book to Learn Python:

1. Structured Learning Path:

  • Start with Basics: Begin your journey by tackling questions related to Python’s basic data types, variables, and control flow structures. This foundational knowledge is crucial for grasping more complex concepts.
  • Progress to Advanced Topics: Gradually move on to more sophisticated topics such as classes and objects, exception handling, and file operations. Each section builds upon the previous one, ensuring a cohesive learning experience.

2. Question and Answer Format:

  • Read Each Question Carefully: Approach each question as a mini-challenge. Attempt to solve it on your own before looking at the solution.
  • Check the Explanation: Regardless of whether you answered correctly, read the explanation provided. This will reinforce what you did right or help you understand where you went wrong.

3. Practical Application:

  • Apply What You Learn: After understanding a concept through a question, write a small piece of code to apply what you’ve learned. This could be enhancing the original question or solving a similar problem.
  • Experiment with Variations: Modify the questions to change their complexity or scope. This experimentation will deepen your understanding and adaptability.

4. Review and Reflect:

  • Regular Reviews: Periodically review sections to refresh your knowledge. This repetition will help solidify your understanding and recall of Python concepts.
  • Self-Assessment: Use the questions as a way to test your knowledge periodically. This can help gauge your progress and identify areas needing further study.

5. Preparation for Interviews:

  • Simulate Interviews: Use the questions to simulate real-world interview scenarios. Try to solve each problem within a set time limit to enhance your problem-solving speed and efficiency.
  • Understand Common Pitfalls: The explanations can help you learn the common mistakes to avoid, which is particularly useful during technical interviews.

6. Group Study:

  • Study Groups: Engage with study groups or online forums to discuss the questions and their solutions. Teaching a concept to someone else is a great way to reinforce your own understanding.
  • Challenge Peers: Try creating challenges for each other based on the questions in the book. This can make learning a more engaging and interactive experience.

“Python Mastery: 350 Questions to Sharpen Your Skills” is more than just a question bank; it’s a guided tour through the Python programming language, designed to equip you with the skills to solve practical problems efficiently. Whether you are preparing for a job interview, improving your programming skills, or teaching Python, this book serves as an essential tool to achieve those goals. Use it not just to answer questions, but to question your answers and continuously improve your understanding of Python.

Python Questions

What will be the output of the following Python code snippet?

print(8 // 3)

a) 2.67
b) 2
c) 3
d) SyntaxError

Correct Answer: b) 2
Explanation: In Python, the // operator performs integer (or floor) division. It returns the largest possible integer that is less than or equal to the quotient. Therefore, 8 // 3 equals 2 because 2 is the largest integer less than 2.67.

What does the strip() method do when applied to a string?

example = ” Python “

print(example.strip())

a) Removes the word ‘Python’
b) Trims leading and trailing spaces
c) Converts all characters to lowercase
d) Splits the string into a list

Correct Answer: b) Trims leading and trailing spaces
Explanation: The strip() method removes any leading and trailing whitespace from a string, including spaces, tabs, and new lines. In the example, example.strip() returns ‘Python’.

Which of the following is a correct way to define a dictionary in Python?

a) my_dict = dict(“key1″=”value1”, “key2″=”value2”)
b) my_dict = {“key1”: “value1”, “key2”: “value2”}
c) my_dict = [“key1” = “value1”, “key2” = “value2”]
d) my_dict = (“key1”: “value1”, “key2”: “value2”)

Correct Answer: b) my_dict = {“key1”: “value1”, “key2”: “value2”}
Explanation: In Python, dictionaries are defined with curly braces {} and use a key-value pairing system, separated by colons :. Option b correctly demonstrates this syntax.

What is the result of this code?

def func(x):

 return x * x

result = func(5)

print(result)

a) 25
b) 10
c) 5
d) None

Correct Answer: a) 25
Explanation: The function func takes a number x and returns its square (x * x). When called with the argument 5, the function returns 25.

What is a correct syntax to output the type of a variable or object in Python?

a) print(typeOf(variable))
b) print(type variable)
c) print(type(variable))
d) print(typeof(variable))

Correct Answer: c) print(type(variable))
Explanation: The type() function is used to determine the data type of a given variable or object. The correct syntax is type(variable).

How do you insert an item at a specific index in a list in Python?

a) list.add(2, ‘item’)
b) list.append(2, ‘item’)
c) list.insert(2, ‘item’)
d) list.set(2, ‘item’)

Correct Answer: c) list.insert(2, ‘item’)
Explanation: The insert() method is used to add an item at a specific index in a list. The first argument is the index, and the second is the item to be inserted.

Which of the following will create an infinite loop?

a) while True: print(“Hello”)

b) while False: print(“Hello”)

c) for i in range(10): print(“Hello”)

d) for i in iter(int, 1): print(“Hello”)

Correct Answer: a) while True: print(“Hello”)
Explanation: The while True: loop will continue indefinitely because the condition True is always true.

What is the correct way to handle exceptions in Python?

a) try: … except ErrorType: …
b) try: … except: …
c) try: … catch ErrorType: …
d) try: … error: …

Correct Answer: a) try: … except ErrorType: …
Explanation: The proper syntax for handling exceptions in Python involves a try block followed by an except block, specifying the type of Error to catch.

What is the output of this code?

x = [“apple”, “banana”, “cherry”]

y = x

y[1] = “kiwi”

print(x)

a) [“apple”, “banana”, “cherry”]
b) [“apple”, “kiwi”, “cherry”]
c) [“apple”, “banana”, “kiwi”]
d) SyntaxError

Correct Answer: b) [“apple”, “kiwi”, “cherry”]
Explanation: Lists in Python are mutable and assigning y = x does not create a copy but rather a reference. Changing y also changes x.

Which keyword is used to create a function in Python?

a) func
b) def
c) function
d) create

Correct Answer: b) def
Explanation: In Python, def is used to define a function. This keyword is followed by the function name and parentheses which can include parameters.

What is the purpose of the pass statement in Python?

def my_function():

 pass

a) Exits the program
b) Acts as a placeholder for future code
c) Throws an error
d) Returns None

Correct Answer: b) Acts as a placeholder for future code
Explanation: The pass statement is used in Python as a placeholder for syntactic purposes where code is eventually required, but no code needs to be executed. It allows the definition of empty loops, functions, and classes, which will not execute any action.

What is the output of the following code?

x = [1, 2, 3]

y = x

x.append(4)

print(y)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4]
d) An error occurs

Correct Answer: b) [1, 2, 3, 4]
Explanation: Lists in Python are mutable objects. Here, y is assigned to the same list as x, so any modifications to x will reflect in y because they reference the same list.

What will the following code print?

if “hello”:

 print(“Yes”)

else:

 print(“No”)

a) Yes
b) No
c) Nothing, it’s an error
d) Yes No

Correct Answer: a) Yes
Explanation: Non-empty strings in Python are considered truthy values. Since “hello” is a non-empty string, the condition in the if statement evaluates to True, and “Yes” is printed.

Which function is used to read a single line from a file in Python?

a) read()
b) readline()
c) readlines()
d) fileopen()

Correct Answer: b) readline()
Explanation: The readline() function reads a single line from the file where the file pointer is currently located and moves the file pointer to the beginning of the next line.

Which of the following methods can be used to combine two lists in Python?

a) extend()
b) append()
c) add()
d) insert()

Correct Answer: a) extend()
Explanation: The extend() method is used to add multiple elements from another list (or any iterable) to the end of the current list, effectively combining them.

What does the enumerate() function return?

a) A list of tuples
b) A generator that yields tuples
c) A list of elements with their indices
d) A tuple of indices and elements

Correct Answer: b) A generator that yields tuples
Explanation: The enumerate() function adds a counter to an iterable and returns it in a form of enumerating object. This object generates pairs that contain the count and the value from the iterable.

What is the output of the following snippet?

nums = [1, 2, 3, 4]

nums *= 2

print(nums)

a) [1, 2, 3, 4, 1, 2, 3, 4]
b) [2, 4, 6, 8]
c) [1, 2, 3, 4, 2, 4, 6, 8]
d) [1, 2, 3, 4] * 2

Correct Answer: a) [1, 2, 3, 4, 1, 2, 3, 4]

Explanation: Multiplying a list by an integer n replicates the list n times. Here, the list nums is replicated twice.

In Python, what is lambda?

a) A data type
b) A library
c) An error type
d) An anonymous function

Correct Answer: d) An anonymous function
Explanation: A lambda function is a small anonymous function defined with the lambda keyword. Lambda functions can have any number of arguments but only one expression.

Which module in Python can be used to generate random numbers?

a) math
b) random
c) rand
d) number

Correct Answer: b) random
Explanation: The random module is used in Python to generate random numbers and to perform random operations like shuffling a list.

What does the following code do?

import functools

@functools.lru_cache(maxsize=128)

def fib(n):

 if n < 2:

 return n

 return fib(n-1) + fib(n-2)

a) Defines a function that calculates factorial
b) Defines a recursive function to calculate Fibonacci numbers with caching
c) Generates a sequence of random numbers
d) Throws a syntax error

Correct Answer: b) Defines a recursive function to calculate Fibonacci numbers with caching
Explanation: The code defines a recursive function to calculate Fibonacci numbers and uses the lru_cache decorator from the functools module to cache the results of the function calls. This optimization significantly improves performance for large n by storing previously computed results of the function up to the maxsize limit.

What does the break statement do in a loop?

for i in range(5):

 if i == 3:

 break

 print(i)

a) Pauses the iteration and continues with the next one
b) Terminates the loop immediately
c) Skips printing the current value and continues with the next loop iteration
d) Prints all values including 3

Correct Answer: b) Terminates the loop immediately
Explanation: The break statement is used to exit a loop prematurely when a specified condition is met. In this example, the loop stops and exits when i equals 3.

What will the following code print?

a = [1, 2, 3]

b = a

b.append(4)

print(a)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4]
d) This code will raise an error

Correct Answer: b) [1, 2, 3, 4]
Explanation: Since b is assigned to a, both a and b refer to the same list in memory. Therefore, modifying b will also change a.

What is a tuple in Python?

a) A mutable collection of ordered items
b) An immutable collection of ordered items
c) A collection of key-value pairs
d) A type of function

Correct Answer: b) An immutable collection of ordered items
Explanation: A tuple is a collection which is ordered and immutable, meaning that its content cannot be changed once it is created.

What does the following function do?

def check_even(num):

 return num % 2 == 0

a) Returns True if the number is odd
b) Returns True if the number is even
c) Increments the number by 2
d) None of the above

Correct Answer: b) Returns True if the number is even
Explanation: The function checks if the remainder when num is divided by 2 is 0, which is true for even numbers, thus returning True for even numbers.

Which statement is used to handle exceptions in Python?

a) handle
b) error
c) except
d) resolve

Correct Answer: c) except
Explanation: The except statement is used in exception handling to catch and handle the exception(s) that are encountered in the try block.

What will be the output of the following code?

print(“Python3.8”.isdigit())

a) True
b) False
c) None
d) This code will raise an error

Correct Answer: b) False
Explanation: The isdigit() method checks whether all the characters in a string are digits. Since “Python3.8” contains non-digit characters, it returns False.

Which of the following is correct syntax to create a set in Python?

a) {1, 2, 3}
b) [1, 2, 3]
c) {“1”: “2”, “3”: “4”}
d) (1, 2, 3)

Correct Answer: a) {1, 2, 3}
Explanation: The correct syntax for creating a set in Python uses curly braces {} with elements separated by commas. Sets are unordered collections of unique elements.

What is the output of the following code snippet?

tuple_a = (1, 2, 3)

tuple_a[1] = 4

print(tuple_a)

a) (1, 4, 3)
b) (1, 2, 3)
c) This code will raise an error
d) None of the above

Correct Answer: c) This code will raise an error
Explanation: Tuples are immutable in Python, meaning you cannot change an element of a tuple after it is created. Trying to do so will raise a TypeError.

How do you create a variable that is private and should not be accessed directly from outside a class in Python?

a) Prefix the variable with an underscore ()
b) Prefix the variable with two underscores ()
c) Prefix the variable with three underscores ()
d) There is no way to enforce privacy in Python, it’s only a convention

Correct Answer: b) Prefix the variable with two underscores (__)
Explanation: Prefixing a variable name with two underscores (__) in a class makes it a weak “private” variable, meaning it cannot be accessed directly from outside the class easily, though it’s still technically accessible.

Which operator is overloaded by the __add__() method for custom objects?

a) –
b) *
c) +
d) /

Correct Answer: c) +
Explanation: The __add__() method in Python is used to define the behavior of the addition operator + for instances of a class, allowing for the customization of how objects are added together.

What is the output of the following code snippet?

x = “Python is fun”

y = x.split()

print(y)

a) “Python is fun”
b) [“Python”, “is”, “fun”]
c) [“Pythonisfun”]
d) [“Python”, “is fun”]

Correct Answer: b) [“Python”, “is”, “fun”]
Explanation: The split() method splits a string into a list where each word is a list item. The default separator is any whitespace.

Which data type would you typically use to store a username and password combination?

a) List
b) Set
c) Dictionary
d) Tuple

Correct Answer: c) Dictionary
Explanation: Dictionaries in Python are ideal for storing key-value pairs. Storing usernames and their corresponding passwords as dictionary keys and values is a common practice.

What does the continue statement do in a loop?

for i in range(5):

 if i == 3:

 continue

 print(i)

a) Stops the loop
b) Skips the rest of the code inside the loop for the current iteration
c) Restarts the loop
d) None of the above

Correct Answer: b) Skips the rest of the code inside the loop for the current iteration
Explanation: The continue statement immediately skips the remaining code inside the loop for the current iteration and moves the loop to the next iteration.

Which module would you import to work with regular expressions in Python?

a) regex
b) re
c) regexp
d) string

Correct Answer: b) re
Explanation: The re module provides support for working with regular expressions. It includes functions to search, split, and replace patterns in strings.

How do you check if “apple” is in the list fruits?

fruits = [“banana”, “cherry”, “apple”]

a) “apple” in fruits
b) fruits.contains(“apple”)
c) fruits.has(“apple”)
d) “apple” exists fruits

Correct Answer: a) “apple” in fruits
Explanation: The in keyword is used to check if an item exists within an iterable, like a list, in Python.

What is slicing in Python?

a) Cutting off the first and last elements of a list
b) Dividing a list into three equal parts
c) Extracting particular elements from an iterable
d) Removing an element from a list without causing an error

Correct Answer: c) Extracting particular elements from an iterable
Explanation: Slicing is a feature that enables accessing parts of sequences like lists, tuples, and strings, using a range of indices.

What will the following code return?

nums = [10, 20, 30, 40]

print(nums.index(30))

a) 2
b) 30
c) 3
d) An error

Correct Answer: a) 2
Explanation: The index() method returns the first index at which a given element appears in the list. Since 30 is at index 2, that is what is returned.

Which keyword is used to declare asynchronous functions in Python?

a) async
b) await
c) asyncio
d) asyn

Correct Answer: a) async
Explanation: The async keyword is used to define asynchronous functions, which allow you to write concurrency code using async and await.

What does the pop() method do to a list?

a) Appends an item to the end of the list
b) Removes and returns the last item of the list
c) Sorts the list
d) Reverses the list

Correct Answer: b) Removes and returns the last item of the list
Explanation: The pop() method removes the item at the given index from the list and returns it. If no index is specified, it removes and returns the last item.

How do you create a shallow copy of a list?

a) new_list = old_list
b) new_list = list(old_list)
c) new_list = old_list[:]
d) Both b and c are correct

Correct Answer: d) Both b and c are correct
Explanation: Both new_list = list(old_list) and new_list = old_list[:] create a shallow copy of old_list. The original and the copy are independent of each other in terms of their contents.

Which function is used to measure the execution time of small code snippets in Python?

a) time.process_time()

b) time.perf_counter()

c) timeit.timeit()

d) time.clock()

Correct Answer: c) timeit.timeit()

Explanation: The timeit.timeit() function is designed to measure the execution time of small code snippets for performance testing by executing the code several times and averaging the results.

What is the correct way to declare a global variable inside a function in Python?

def myfunc():

 global x

 x = 10

a) Declare the variable outside the function

b) Use the global keyword inside the function

c) Declare it as global x = 10

d) Use the extern keyword

Correct Answer: b) Use the global keyword inside the function

Explanation: The global keyword is used inside a function to declare that x is a global variable, allowing the function to modify the variable defined outside its scope.

Which of the following is NOT a built-in data type in Python?

a) list

b) set

c) tree

d) dict

Correct Answer: c) tree

Explanation: Python has several built-in data types like lists, sets, and dictionaries, but tree is not one of them as there is no built-in tree data structure.

What is the output of the following code?

x = True

y = False

z = False

if not x or y:

 print(1)

elif not x or not y and z:

 print(2)

elif not x or y or not y and x:

 print(3)

else:

 print(4)

a) 1
b) 2
c) 3
d) 4

Correct Answer: a) 1
Explanation: The condition if not x or y: evaluates to False or False which is False, but due to the not x (which is False) combined with y (which is also False), the first statement is selected because the conditions of the elif statements are not satisfied.

What does the len() function return when used on a dictionary?

a) The number of keys in the dictionary

b) The number of values in the dictionary

c) The sum of keys and values

d) None of the above

Correct Answer: a) The number of keys in the dictionary

Explanation: The len() function, when used on a dictionary, returns the number of keys in the dictionary. len() also works on other collection types like lists, tuples, and sets, returning the number of elements in each case.

Which of the following is a correct syntax to check if a key exists in a dictionary?

my_dict = {“a”: 1, “b”: 2, “c”: 3}

a) “a” in my_dict.keys()

b) “a” in my_dict

c) my_dict.exists(“a”)

d) Both a and b are correct

Correct Answer: d) Both a and b are correct

Explanation: You can check if a key exists in a dictionary either by “a” in my_dict.keys() or simply “a” in my_dict. Both methods are correct.

How can you concatenate the following two lists to create a third list?

list_one = [1, 2, 3]

list_two = [4, 5, 6]

a) list_three = list_one.append(list_two)

b) list_three = list_one + list_two

c) list_three = list_one.extend(list_two)

d) list_three = list_one & list_two

Correct Answer: b) list_three = list_one + list_two

Explanation: The + operator is used to concatenate lists in Python, resulting in a new list that combines elements from both lists.

Which of the following is the correct way to create a new set that contains elements in both set A and set B?

A = {1, 2, 3}

B = {3, 4, 5}

a) C = A | B

b) C = A & B

c) C = A + B

d) C = A – B

Correct Answer: b) C = A & B

Explanation: The & operator is used in Python to perform a set intersection, which returns a new set containing only the elements that are common to both sets. In this case, A & B will evaluate to {3}, since 3 is the only element that appears in both set A {1, 2, 3} and set B {3, 4, 5}. This operation does not modify the original sets A or B but instead creates a new set that includes the elements found in both.

What is the output of the following list comprehension?

result = [i for i in range(10) if i % 2 == 0]

a) [0, 2, 4, 6, 8]
b) [1, 3, 5, 7, 9]
c) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
d) [1, 2, 3, 4, 5]

Correct Answer: a) [0, 2, 4, 6, 8]
Explanation: This list comprehension iterates through numbers 0 to 9, including only those that are even (i.e., divisible by 2 without remainder).

Which keyword is used to import a module in Python?

a) import
b) module
c) load
d) use

Correct Answer: a) import
Explanation: The import keyword is used to load other Python source code files as modules into the current program.

Which method can you use to remove any element from a set?

a) pop()
b) remove()
c) delete()
d) clear()

Correct Answer: a) pop()
Explanation: The pop() method removes a random element from the set and returns the removed element. Note that remove() also deletes an element, but it requires a specific element to delete and does not return it.

How do you reverse the order of elements in a list in-place?

a) list.reverse()
b) list.reversed()
c) reverse(list)
d) list.sort(reverse=True)

Correct Answer: a) list.reverse()
Explanation: The list.reverse() method reverses the elements of the list in-place, i.e., it modifies the list directly.

What will be the output of this code?

a = [1, 2, 3]

b = a

a += [4, 5]

print(b)

a) [1, 2, 3]
b) [1, 2, 3, 4, 5]
c) [4, 5]
d) Syntax error

Correct Answer: b) [1, 2, 3, 4, 5]
Explanation: The += operation modifies the list in-place. Since b is a reference to the same list as a, the changes reflect in b as well.

What does the else clause do in a Python try block?

a) Executes if the try block raises an error
b) Always executes after the try block, regardless of whether an error was raised
c) Executes if the try block does not raise an error
d) None of the above

Correct Answer: c) Executes if the try block does not raise an error
Explanation: The else clause in a try block runs if the code within the try did not raise any exceptions.

Which of the following is true about Python tuples?

a) Tuples are mutable
b) Tuples can contain only numeric data
c) Tuples are immutable
d) Tuples do not preserve the order of elements

Correct Answer: c) Tuples are immutable
Explanation: Tuples are like lists except that they are immutable, meaning they cannot be changed once they are created.

What is the correct syntax for defining a class named Car?

a) class Car():
b) class Car:
c) define Car:
d) new class Car:

Correct Answer: b) class Car:
Explanation: The correct syntax to define a class in Python simply uses the keyword class followed by the class name and a colon.

What is None in Python?

a) A function that does nothing
b) The ‘null’ value of Python
c) A special data type for handling numeric operations
d) An error type

Correct Answer: b) The ‘null’ value of Python
Explanation: None is the object that represents the absence of a value or a null

What is the return type of a lambda function?

a) int

b) bool

c) function

d) None

Correct Answer: c) function
Explanation: A lambda function in Python is an anonymous function expressed as a single statement. It returns a function object.

What is the output of the following expression?

‘Hello’ == “Hello”

a) True

b) False

c) SyntaxError

d) TypeError

Correct Answer: a) True
Explanation: In Python, single quotes (‘) and double quotes (“) are used interchangeably to define strings, so the strings ‘Hello’ and “Hello” are considered equal.

Which collection is ordered, changeable, and allows duplicate members?

a) Set

b) Tuple

c) List

d) Dictionary

Correct Answer: c) List
Explanation: A list is an ordered and changeable collection that allows duplicate members, making it one of the most versatile collection types in Python.

Which method is used to convert a JSON string into a Python dictionary?

a) json.loads()

b) json.dumps()

c) json.load()

d) json.dump()

Correct Answer: a) json.loads()
Explanation: The json.loads() method parses a JSON formatted string and returns a Python dictionary.

What does the @staticmethod decorator do?

a) Indicates that a method is static, belonging to the class rather than the instance

b) Converts a method into a static variable

c) Prevents a method from being overridden in subclasses

d) Automatically calls a method when a class is created

Correct Answer: a) Indicates that a method is static, belonging to the class rather than the instance
Explanation: The @staticmethod decorator is used to define a method that does not operate on an instance of the class nor modify the class state.

What keyword is used to create a variable-length argument list in Python functions?

a) *args

b) **kwargs

c) *varargs

d) **args

Correct Answer: a) *args
Explanation: The *args keyword is used to pass a variable number of non-keyword arguments to a function.

Which module provides capabilities to work with dates and times in Python?

a) time

b) datetime

c) timelib

d) datelib

Correct Answer: b) datetime
Explanation: The datetime module supplies classes for manipulating dates and times in both simple and complex ways.

How can you remove duplicates from a list in Python?

a) Convert the list to a set and back to a list

b) Use the list.unique() method

c) Use the list.remove_duplicates() method

d) Use a for loop to filter duplicates manually

Correct Answer: a) Convert the list to a set and back to a list
Explanation: Converting a list to a set is a commonly used technique to remove duplicates because sets cannot contain duplicate items. Converting it back to a list retains only the unique items.

What does the globals() function do?

a) Returns a list of all global variables

b) Returns a dictionary of the current global symbol table

c) Clears all global variables

d) Creates a new global variable

Correct Answer: b) Returns a dictionary of the current global symbol table
Explanation: The globals() function returns a dictionary representing the current global symbol table, which is always the dictionary of the current module.

In Python, what will happen if you try to compile a file with syntax errors?

a) The interpreter will correct the errors automatically.

b) The file will compile with warnings.

c) The interpreter will fail with a SyntaxError.

d) The file will compile but fail during execution.

Correct Answer: c) The interpreter will fail with a SyntaxError
Explanation: Python checks for syntax during the compilation phase. If it encounters syntax errors, it raises a SyntaxError and halts the compilation process.

What is the output of the following code snippet?

print(2 ** 3)

a) 8
b) 6
c) 9
d) 5

Correct Answer: a) 8
Explanation: The ** operator in Python is used for exponentiation. .

Which of the following correctly checks if a list is empty?

a) if not list:
b) if list == None:
c) if list == ’empty’:
d) if list == 0:

Correct Answer: a) if not list:
Explanation: In Python, empty lists evaluate to False. Therefore, if not list: is the correct way to check if a list is empty.

How do you create a complex number in Python?

a) complex(real, imag)
b) complex = real + imag
c) real + imag * j
d) real + imag * i

Correct Answer: a) complex(real, imag)
Explanation: In Python, complex numbers can be created using the complex(real, imag) function, where real and imag represent the real and imaginary parts, respectively.

What is the output of the following code?

nums = {1, 2, 2, 3, 3, 3}

print(len(nums))

a) 6
b) 3
c) 4
d) 5

Correct Answer: c) 4
Explanation: A set in Python does not allow duplicate elements. The set nums will contain only unique elements, {1, 2, 3}, so the length is 3.

What built-in Python function will return the highest number in a list?

a) max()
b) high()
c) top()
d) peak()

Correct Answer: a) max()
Explanation: The max() function returns the largest item in an iterable or the largest of two or more arguments.

What does the zip() function do?

a) Compresses the given iterable
b) Decompresses the given iterable
c) Combines several iterables into one sequence of tuples
d) Splits a list into multiple smaller lists

Correct Answer: c) Combines several iterables into one sequence of tuples
Explanation: The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

What keyword is used to define a class inheritance in Python?

a) extends
b) inherits
c) class
d) super

Correct Answer: c) class
Explanation: Inheritance is defined by using the class declaration. For example, class Derived(Base) means Derived inherits from Base.

Which of the following would correctly open a file for reading only?

a) open(‘file.txt’, ‘r’)
b) open(‘file.txt’, ‘w’)
c) open(‘file.txt’, ‘a’)
d) open(‘file.txt’, ‘x’)

Correct Answer: a) open(‘file.txt’, ‘r’)
Explanation: The ‘r’ mode in the open() function specifies that the file is to be opened for reading only.

What does the del statement do?

a) Deletes variables or parts of a list
b) Clears the content of a text file
c) Declares a deletion
d) None of the above

Correct Answer: a) Deletes variables or parts of a list
Explanation: The del statement is used to delete objects in Python. It can remove individual variables, items within data structures, or entire data structures.

What is the correct way to handle multiple exceptions in one block?

a) except(TypeError, ValueError):
b) except TypeError or ValueError:
c) except(TypeError and ValueError):
d) except TypeError, ValueError:

Correct Answer: a) except(TypeError, ValueError):
Explanation: To handle multiple different exceptions in the same except block, you list the exception types as a tuple after the except keyword.

Which Python library is primarily used for data analysis and manipulation?

a) numpy

b) matplotlib

c) pandas

d) scipy

Correct Answer: c) pandas

Explanation: pandas is a popular Python library used primarily for data manipulation and analysis. It provides data structures and operations for manipulating numerical tables and time series.

What will be the output of the following code snippet?

x = [‘a’, ‘b’, ‘c’, ‘d’]

print(”.join(x))

a) abcd

b) [‘a’, ‘b’, ‘c’, ‘d’]

c) a b c d

d) None

Correct Answer: a) abcd

Explanation: The join() method concatenates all the elements in the list into a single string, with each element being joined by the string on which join() is called—in this case, an empty string.

What method is used to add an element to the end of a list in Python?

a) push()

b) append()

c) insert()

d) extend()

Correct Answer: b) append()

Explanation: The append() method is used to add an item to the end of a list.

How do you create a static method in a Python class?

a) Use the @staticmethod decorator before the method definition.

b) Define the method outside of any class.

c) Use the static keyword before the method definition.

d) Define the method within a constructor.

Correct Answer: a) Use the @staticmethod decorator before the method definition.

Explanation: Static methods in Python are created by placing the @staticmethod decorator above the method definition. This indicates that the method is related to the class but does not operate on an instance of the class.

Which keyword is used to define asynchronous functions that can use await?

a) async

b) await

c) asyncio

d) asynchronous

Correct Answer: a) async

Explanation: The async keyword is used to declare a function as asynchronous and allows it to use await to call other async functions.

What will the following code output?

d = {“john”: 40, “peter”: 45}

print(list(d.keys()))

a) [“john”, “peter”]

b) [“john”: 40, “peter”: 45]

c) [40, 45]

d) None

Correct Answer: a) [“john”, “peter”]

Explanation: The keys() method returns a view object that displays a list of all the keys in the dictionary, which can be converted to a list using the list() function.

What built-in function can you use to get the length of a string in Python?

a) len()

b) count()

c) size()

d) length()

Correct Answer: a) len()

Explanation: The len() function is used to determine the length of various data types, including strings, lists, and dictionaries in Python.

What type of loop will continue to execute as long as its condition remains true?

a) Do-while loop

b) For loop

c) While loop

d) Conditional loop

Correct Answer: c) While loop

Explanation: A while loop in Python repeatedly executes the target statement as long as the given condition is true.

Which error is thrown when trying to access a non-existent dictionary key?

a) ValueError

b) KeyError

c) IndexError

d) NameError

Correct Answer: b) KeyError

Explanation: A KeyError is raised when a dictionary key is not found in the set of existing keys.

What is the correct way to declare a constructor in a Python class?

a) def __init__(self):

b) def __constructor__(self):

c) def Constructor(self):

d) def new(self):

Correct Answer: a) def __init__(self):

Explanation: In Python, the constructor function is named __init__. It’s automatically called when a new object instance of the class is created.

Which function allows you to measure the performance time of small bits of Python code?

a) time.clock()

b) timeit.timeit()

c) time.perf_counter()

d) time.process_time()

Correct Answer: b) timeit.timeit()

Explanation: The timeit.timeit() function is designed to measure the execution time of small code snippets for performance testing by executing the code repeatedly and averaging the results.

What is the result of the following Python slice?

lst = [10, 20, 30, 40, 50]

result = lst[1:4]

a) [20, 30, 40, 50]

b) [20, 30, 40]

c) [10, 20, 30]

d) [30, 40, 50]

Correct Answer: b) [20, 30, 40]

Explanation: Slicing in Python is zero-based; the index before the colon is where the slice starts (inclusive), and the index after is where it stops (exclusive). Therefore, lst[1:4] includes elements at indices 1, 2, and 3.

What keyword is used to check if an object is an instance of a particular class or type?

a) is

b) check

c) type

d) instanceof

Correct Answer: d) instanceof

Explanation: The isinstance() function is used to check if an object is an instance of a particular class or type in Python. For example, isinstance(x, int) would check if x is an instance of the int class.

How do you round a number to the nearest integer in Python?

a) round(number)

b) math.round(number)

c) number.round()

d) int(number)

Correct Answer: a) round(number)

Explanation: The built-in round() function rounds a floating-point number to the nearest integer or specified number of decimal places.

What is the default behavior of the sort() method on a list?

a) Sorts the list in ascending numerical or lexicographical order

b) Sorts the list in descending numerical or lexicographical order

c) Randomizes the list

d) Reverses the list

Correct Answer: a) Sorts the list in ascending numerical or lexicographical order

Explanation: The sort() method sorts the list in-place in ascending order by default, unless otherwise specified with the reverse=True parameter.

What will the following code output?

a = “Hello, World!”

print(a[7])

a) ,

b) W

c) o

d) Hello

Correct Answer: b) W

Explanation: In Python, string indexing is zero-based, so a[7] refers to the eighth character of the string “Hello, World!”, which is W.

Which Python data type would you use to store a collection of values that need to remain in the order they were added and must be unique?

a) List

b) Set

c) Tuple

d) OrderedDict

Correct Answer: d) OrderedDict

Explanation: An OrderedDict, unlike a standard dictionary or set, maintains the order of keys as they were added. Sets do not maintain order, and lists do not enforce uniqueness.

How do you execute a block of code repeatedly at fixed intervals of time in Python?

a) Using a while loop with a time.sleep() inside

b) Using the repeat() method of a list

c) Using a for loop with a delay

d) Using the timeit module repeatedly

Correct Answer: a) Using a while loop with a time.sleep() inside

Explanation: To execute a block of code repeatedly at fixed intervals, you can use a while loop that runs indefinitely or until a certain condition is met, with time.sleep() to pause execution for the desired amount of time between iterations.

What method is used to remove the first occurrence of a specific element from a list?

a) pop()

b) remove()

c) delete()

d) discard()

Correct Answer: b) remove()

Explanation: The remove() method removes the first occurrence of a specific element from a list. If the element is not found, it raises a ValueError.

What will the following code output?

def test(var=[]):

 var.append(1)

 return var

print(test())

print(test())

a) [1] and [1]

b) [1] and [1, 1]

c) [1, 1] and [1, 1]

d) [] and [1]

Correct Answer: b) [1] and [1, 1]

Explanation: The function test() uses a mutable default argument. Mutable default arguments retain any changes made to them between function calls. Therefore, each call to test() continues to append to the same list.

Which Python feature allows for the iteration over both the elements and their indices in a list?

a) enumerate()

b) iterator()

c) range()

d) zip()

Correct Answer: a) enumerate()

Explanation: The enumerate() function adds a counter to an iterable and returns it as an enumerate object. This object generates pairs that contain the count (index) and the value from the iterable.

Which of the following is not a core data type in Python?

a) int

b) str

c) bool

d) array

Correct Answer: d) array

Explanation: array is not a core data type in Python’s standard set of built-ins. It is available through the array module, which provides a space-efficient way of storing homogeneous data types. Python’s core simple data types include int, str, and bool.

Which function would you use to find the integer part of a division operation in Python?

a) div()

b) int()

c) //

d) mod()

Correct Answer: c) //

Explanation: The floor division operator // divides two numbers and rounds down to the nearest whole number to get the integer part of the division.

What does the finally block do in a try-except statement?

a) It runs if the try block raises an error.

b) It runs regardless of whether an exception was caught or not.

c) It skips the execution of the try block.

d) It handles all exceptions not caught by previous blocks.

Correct Answer: b) It runs regardless of whether an exception was caught or not.

Explanation: The finally block in a try-except statement will execute as the last step in the try-except process, regardless of whether an exception occurred or not. It’s often used for clean-up actions.

What is the correct way to declare a dictionary that maps integers to their squares for numbers from 1 to 5?

a) {x: x*x for x in range(1, 6)}

b) [x: x*x for x in range(1, 6)]

c) (x: x*x for x in range(1, 6))

d) None of the above

Correct Answer: a) {x: x*x for x in range(1, 6)}

Explanation: Dictionary comprehensions in Python allow the creation of dictionaries using an iterable, in this case range(1, 6), mapping each x to its square.

What is the output of this function call?

def add(*args):

 return sum(args)

print(add(1, 2, 3, 4, 5))

a) 15

b) [1, 2, 3, 4, 5]

c) None

d) Error

Correct Answer: a) 15

Explanation: The add function uses *args to take any number of positional arguments, sums them using the built-in sum() function, and returns the result.

Which method would you use to replace parts of a string with another string?

a) replace()

b) swap()

c) change()

d) edit()

Correct Answer: a) replace()

Explanation: The replace() method in Python strings replaces occurrences of a specified substring with another substring.

What built-in Python function will compile a string of Python code?

a) exec()

b) evaluate()

c) compile()

d) run()

Correct Answer: c) compile()

Explanation: The compile() function is used to compile source into code or AST objects, which can then be executed by exec() or eval().

What data type is the variable x after this assignment: x = {1, 2, 3, 2, 1}?

a) List

b) Dictionary

c) Set

d) Tuple

Correct Answer: c) Set

Explanation: Curly braces {} containing a series of integers define a set, which automatically removes duplicate entries.

Which method is used to find the position of an element in a list?

a) find()

b) locate()

c) index()

d) position()

Correct Answer: c) index()

Explanation: The index() method returns the first index at which a given element can be found in the list.

How can you generate random floating-point numbers between 0.0 and 1.0?

a) random.randint(0, 1)

b) random.range(0.0, 1.0)

c) random.random()

d) random.int()

Correct Answer: c) random.random()

Explanation: The random.random() function generates a random float number between 0.0 and 1.0.

What will happen if a file is opened with mode x in Python?

a) Opens a file for exclusive creation. If the file already exists, the operation fails.

b) Extracts data from the file without deleting it.

c) Executes the file as a Python script.

Correct Answer: a) Opens a file for exclusive creation. If the file already exists, the operation fails.

Explanation: The ‘x’ mode in Python’s open() function is used for creating and opening a file exclusively. If the file already exists, the function will raise a FileExistsError, preventing any data from being overwritten. This mode is particularly useful when you want to ensure that no data is lost by not accidentally overwriting an existing file.

What will be the output of the following code snippet?

list1 = [‘a’, ‘b’, ‘c’]

list2 = list1

list2.append(‘d’)

print(list1)

a) [‘a’, ‘b’, ‘c’]
b) [‘a’, ‘b’, ‘c’, ‘d’]
c) [‘d’]
d) None

Correct Answer: b) [‘a’, ‘b’, ‘c’, ‘d’]
Explanation: Since list2 is assigned to list1, they both reference the same list. Any modification to list2 affects list1 as well.

Which function in Python can be used to read only a single character from the standard input?

a) input()
b) raw_input()
c) sys.stdin.read(1)
d) getch()

Correct Answer: c) sys.stdin.read(1)
Explanation: The sys.stdin.read(1) function reads a single character from the standard input. The input() function reads a line.

Which of the following is an immutable data type?

a) Lists
b) Dictionaries
c) Tuples
d) Sets

Correct Answer: c) Tuples
Explanation: Tuples are immutable data types in Python, meaning once a tuple is created, its contents cannot be altered.

What is the use of the else clause in Python loops?

a) To run a block of code if the loop didn’t break
b) To handle exceptions that might occur in the loop
c) To add additional conditions to the loop
d) To execute a block of code before the loop starts

Correct Answer: a) To run a block of code if the loop didn’t break
Explanation: In Python, the else clause in loops executes a block of code once when the loop condition is no longer true but only if the loop has not been terminated by a break statement.

How can you make an HTTP request in Python?

a) Using the http library
b) Using the requests module
c) Using the HTTP class
d) Using the Socket module

Correct Answer: b) Using the requests module
Explanation: The requests module is a popular HTTP library used in Python for making HTTP requests to a specified URL.

What is the difference between @staticmethod and @classmethod in Python?

a) @staticmethod doesn’t pass any extra arguments, but @classmethod passes a reference to the class (cls) as the first argument.
b) @staticmethod passes a reference to the instance (self) as the first argument, while @classmethod does not.
c) @classmethod is used to declare a constructor.
d) No difference, they are just two different names for the same functionality.

Correct Answer: a) @staticmethod doesn’t pass any extra arguments, but @classmethod passes a reference to the class (cls) as the first argument.
Explanation: @staticmethod defines a method that behaves like a plain function that operates on neither the instance nor the class, whereas @classmethod affects the class as it receives a class reference as the first argument.

Which of the following is true when using Python’s file open() function with the ‘b’ mode?

a) The file is opened in binary mode.
b) The file is opened in big-endian mode.
c) The file buffer is flushed before opening.
d) The file is opened in backward mode, reading from end to start.

Correct Answer: a) The file is opened in binary mode.
Explanation: Opening a file with ‘b’ mode in Python specifies binary mode, which is used for non-text files such as images or sound files.

What does the globals() function return in Python?

a) A list of all global symbols.
b) A dictionary representing the current global symbol table.
c) A list of all local symbols.
d) None of the above.

Correct Answer: b) A dictionary representing the current global symbol table.
Explanation: The globals() function returns a dictionary containing the variables defined in the global namespace.

What is pylint?

a) A Python package manager.
b) A Python compiler.
c) A Python code linter.
d) A Python version management tool.

Correct Answer: c) A Python code linter.
Explanation: pylint is a tool that checks for errors in Python code, enforces a coding standard, and looks for code smells. It can also suggest improvements and ensure that code conforms to Python coding standards.

Which of the following methods is used to remove and return an element from a list at a given index?

a) pop(index)
b) push(index)
c) pull(index)
d) drop(index)

Correct Answer: a) pop(index)
Explanation: The pop() method removes and returns the element at the specified position (index) in the list. If no index is specified, pop() removes and returns the last item in the list.

Which keyword in Python is used to define an anonymous function?

a) func

b) lambda

c) anon

d) def

Correct Answer: b) lambda
Explanation: The lambda keyword is used in Python to create anonymous functions, which are functions that are defined without a name. They are often used for short, ad-hoc functions.  lambda functions are limited to a single expression and are often used for short, simple functions.

What will be the output of the following Python code snippet?

x = 5

y = 3

print(x ** y)

a) 15
b) 125
c) 8
d) 2

Correct Answer: b) 125
Explanation: The ** operator is used for exponentiation in Python. 

What method should be used to convert a Python object to a string that is formatted as a JSON object?

a) json.dumps()

b) json.loads()

c) json.stringify()

d) json.parse()

Correct Answer: a) json.dumps()
Explanation: The json.dumps() method converts a Python object into a JSON formatted string.

Which of the following is not a valid Python data type?

a) list

b) set

c) array

d) map

Correct Answer: d) map
Explanation: map is not a data type in Python; it is a built-in function used to apply a function to all the items in an iterable.

How can you remove all items from a list in Python?

a) list.deleteAll()

b) list.removeAll()

c) list.clear()

d) list.erase()

Correct Answer: c) list.clear()
Explanation: The list.clear() method removes all items from the list, leaving it empty.

What does the is operator do in Python?

a) Checks if two variables are equal

b) Checks if two variables are identical and refer to the same object

c) Checks if two variables have the same type

d) None of the above

Correct Answer: b) Checks if two variables are identical and refer to the same object
Explanation: The is operator in Python is used to test if two variables refer to the same object, not just if they are equal.

What built-in Python function returns a sequence of numbers starting from 0 by default and increments by 1 (by default), and stops before a specified number?

a) range()

b) numbers()

c) sequence()

d) list()

Correct Answer: a) range()
Explanation: The range() function returns a sequence of numbers, starting from 0 if no start value is specified, increments by 1 if no step value is specified, and stops before a specified number.

In Python, how do you check if a variable x is an instance of the float type?

a) type(x) == float

b) x instanceof float

c) x.type() == float

d) isinstance(x, float)

Correct Answer: d) isinstance(x, float)
Explanation: The isinstance() function checks if the object (first argument) is an instance of the class or a subclass thereof (second argument).

What is the default encoding for Python source code files?

a) ASCII

b) UTF-8

c) UTF-16

d) ANSI

Correct Answer: b) UTF-8
Explanation: As of Python 3.x, the default encoding for Python source code files is UTF-8.

What is the term for a function defined inside another function in Python?

a) Nested function

b) Internal function

c) Enclosed function

d) Sub function

Correct Answer: a) Nested function
Explanation: A function defined inside another function is called a nested function in Python. Nested functions can access variables of the enclosing scope.

What is the term used for a variable declared outside a function that is accessible inside the function in Python?

a) Local variable

b) Global variable

c) External variable

d) Public variable

Correct Answer: b) Global variable
Explanation: A global variable is declared outside a function and is accessible and modifiable by functions within the same module.

Which of the following will correctly import only the sqrt function from the math module?

a) import sqrt from math

b) import math.sqrt

c) from math import sqrt

d) import math as sqrt

Correct Answer: c) from math import sqrt
Explanation: The statement from math import sqrt imports only the sqrt function from the math module, allowing it to be used without prefixing it with math..

What will the following code snippet print?

a = [1, 2, 3, 4, 5]

b = a

b[0] = 10

print(a)

a) [1, 2, 3, 4, 5]
b) [10, 2, 3, 4, 5]
c) [1, 10, 3, 4, 5]
d) An error occurs

Correct Answer: b) [10, 2, 3, 4, 5]
Explanation: Since b is assigned the same list a references (not a copy), changes to b are reflected in a. Changing b[0] to 10 modifies the first element of the same list that a points to.

What is a correct way to assert that a variable x should be equal to 10 in Python?

a) assert x == 10
b) assert(x, 10)
c) x == 10 assert
d) assert(x = 10)

Correct Answer: a) assert x == 10
Explanation: The assert statement in Python is used for debugging purposes. It tests if a condition is true and if not, it raises an AssertionError. Here, it checks if x equals 10.

Which module provides functions for manipulating dates and times in both simple and complex ways?

a) times

b) datetime

c) calendar

d) dateutil

Correct Answer: b) datetime
Explanation: The datetime module supplies classes for manipulating dates and times in both simple and complex ways.

What is the output of print(list(range(5, -1, -1)))?

a) [5, 4, 3, 2, 1]
b) [5, 4, 3, 2, 1, 0]
c) [0, 1, 2, 3, 4, 5]
d) [5, 4, 3, 2, 1, -1]

Correct Answer: b) [5, 4, 3, 2, 1, 0]
Explanation: The range() function here starts at 5 and decrements by 1 each step, stopping before reaching -1, thus including 0.

Which method would you use to find the position of the first occurrence of a substring in a string?

a) find()

b) index()

c) position()

d) locate()

Correct Answer: a) find()
Explanation: The find() method returns the lowest index in the string where the substring is found. If the substring is not found, it returns -1.

How do you format strings in Python 3.6 and above with a more readable syntax?

a) String interpolation

b) Concatenation

c) f-strings

d) % formatting

Correct Answer: c) f-strings
Explanation: Introduced in Python 3.6, f-strings offer a concise and readable way to embed expressions inside string literals, using curly braces {}.

What will the following code output?

print(type(1/2))

a) <class ‘int’>
b) <class ‘float’>
c) <class ‘number’>
d) <class ‘decimal’>

Correct Answer: b) <class ‘float’>
Explanation: In Python 3, division of integers using / always results in a float, even if the division is evenly divisible.

Which keyword in Python is used to start a generator comprehension?

a) (x for x in range(10))

b) [x for x in range(10)]

c) {x for x in range(10)}

d) <x for x in range(10)>

Correct Answer: a) (x for x in range(10))
Explanation: Generator comprehensions are defined using parentheses and are used for creating generators without needing a function.