0% found this document useful (0 votes)
3 views64 pages

Python MCQ1

Enjoy?

Uploaded by

r8978428
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views64 pages

Python MCQ1

Enjoy?

Uploaded by

r8978428
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 64

Data abstraction

in Python involves hiding the complex implementation details and exposing only the necessary parts
of the data. This is typically done using classes and objects. Here's a simple example to illustrate data
abstraction:

Example: Bank Account

We'll create a BankAccount class that abstracts away the details of how the balance is managed,
while providing a simple interface for deposit, withdrawal, and checking the balance.

python

Copy code

class BankAccount:

def __init__(self, initial_balance=0):

self.__balance = initial_balance # private attribute

def deposit(self, amount):

if amount > 0:

self.__balance += amount

print(f"Deposited: ${amount}")

else:

print("Deposit amount must be positive.")

def withdraw(self, amount):

if 0 < amount <= self.__balance:

self.__balance -= amount

print(f"Withdrew: ${amount}")

else:

print("Insufficient funds or invalid amount.")

def get_balance(self):

return self.__balance
# Usage

account = BankAccount(100) # Create an account with an initial balance of $100

account.deposit(50) # Deposit $50

account.withdraw(30) # Withdraw $30

print(f"Current Balance: ${account.get_balance()}") # Check balance

Explanation

 Encapsulation: The __balance attribute is private (denoted by the double underscores),


meaning it cannot be accessed directly from outside the class. This helps in hiding the
internal state.

 Public Methods: The deposit, withdraw, and get_balance methods provide a controlled way
to interact with the account. Users of the BankAccount class can deposit, withdraw, and
check the balance without needing to know how the balance is managed internally.

This example demonstrates data abstraction by providing a clean interface for interacting with a bank
account while keeping the details of how the balance is handled hidden from the user.

python encapsulation example

Encapsulation in Python involves bundling data and methods that operate on that data into a single
unit, typically a class, and restricting access to some of the object's components. This helps in hiding
the internal state of the object and only exposing what is necessary.

Here’s a simple example to illustrate encapsulation:

Example: Person Class

We’ll create a Person class where certain details are private, and access to these details is controlled
via public methods.

python

Copy code

class Person:

def __init__(self, name, age):

self.__name = name # Private attribute

self.__age = age # Private attribute

def get_name(self):
return self.__name

def set_name(self, name):

if isinstance(name, str) and name:

self.__name = name

else:

print("Invalid name.")

def get_age(self):

return self.__age

def set_age(self, age):

if isinstance(age, int) and age > 0:

self.__age = age

else:

print("Invalid age.")

# Usage

person = Person("Alice", 30)

print(person.get_name()) # Accessing the name through a public method

print(person.get_age()) # Accessing the age through a public method

person.set_name("Bob") # Setting a new name through a public method

person.set_age(25) # Setting a new age through a public method

print(person.get_name()) # Checking updated name

print(person.get_age()) # Checking updated age

# Attempting to access private attributes directly (will fail)

# print(person.__name) # This will raise an AttributeError


# print(person.__age) # This will also raise an AttributeError

Explanation

 Private Attributes: The attributes __name and __age are private (indicated by double
underscores), meaning they cannot be accessed directly from outside the class. This helps
protect the internal state of the object.

 Public Methods: The methods get_name, set_name, get_age, and set_age are public and
provide controlled access to the private attributes. They allow external code to read or
modify the private attributes in a controlled manner.

In this example, encapsulation ensures that the internal representation of a Person object is hidden,
and changes to the name or age are controlled and validated through public methods. This helps
maintain the integrity of the object’s state and prevents invalid data from being set directly.

polymorphism python

Polymorphism in Python refers to the ability of different objects to be treated as instances of the
same class through a common interface, typically using methods. It allows methods to do different
things based on the object it is acting upon, even though they share the same name.

There are two types of polymorphism in Python:

1. Method Overloading: In Python, method overloading (i.e., defining multiple methods with
the same name but different parameters) is not supported directly as in some other
languages. However, Python’s dynamic typing allows you to achieve similar results by using
default arguments or variable-length arguments.

2. Method Overriding: This occurs when a subclass provides a specific implementation of a


method that is already defined in its superclass. It allows a subclass to modify or extend the
behavior of a method from its superclass.

Example of Method Overriding

Here’s an example using method overriding:

python

Copy code

class Animal:

def speak(self):

raise NotImplementedError("Subclasses must implement this method")

class Dog(Animal):
def speak(self):

return "Woof!"

class Cat(Animal):

def speak(self):

return "Meow!"

def make_animal_speak(animal):

print(animal.speak())

# Usage

dog = Dog()

cat = Cat()

make_animal_speak(dog) # Output: Woof!

make_animal_speak(cat) # Output: Meow!

Explanation

 Superclass (Animal): Defines a method speak that is meant to be overridden by subclasses. It


raises a NotImplementedError to ensure that subclasses provide an implementation.

 Subclasses (Dog and Cat): Each subclass provides its own implementation of the speak
method.

 Polymorphism: The make_animal_speak function takes an Animal object (which can be a


Dog, Cat, or any other subclass) and calls its speak method. The correct method is called
based on the actual type of the object, demonstrating polymorphism.

This allows make_animal_speak to work with any object that has a speak method, regardless of the
specific class of the object, as long as the object follows the expected interface.

4o mini

python inheritance all types with example

Inheritance in Python allows a class (child or subclass) to inherit attributes and methods from
another class (parent or superclass). This promotes code reuse and a hierarchical organization of
classes. Python supports several types of inheritance:
1. Single Inheritance

In single inheritance, a class (subclass) inherits from one superclass.

Example:

python

Copy code

class Animal:

def speak(self):

return "Animal sound"

class Dog(Animal):

def speak(self):

return "Woof!"

# Usage

dog = Dog()

print(dog.speak()) # Output: Woof!

2. Multiple Inheritance

In multiple inheritance, a class inherits from more than one superclass. This can be used to combine
behaviors from multiple classes.

Example:

python

Copy code

class Flyer:

def fly(self):

return "Flying"

class Swimmer:

def swim(self):

return "Swimming"

class Duck(Flyer, Swimmer):


def quack(self):

return "Quack!"

# Usage

duck = Duck()

print(duck.fly()) # Output: Flying

print(duck.swim()) # Output: Swimming

print(duck.quack()) # Output: Quack!

3. Multilevel Inheritance

In multilevel inheritance, a class inherits from a subclass, forming a chain of inheritance.

Example:

python

Copy code

class Animal:

def speak(self):

return "Animal sound"

class Mammal(Animal):

def has_fur(self):

return True

class Dog(Mammal):

def speak(self):

return "Woof!"

# Usage

dog = Dog()

print(dog.speak()) # Output: Woof!

print(dog.has_fur()) # Output: True

4. Hierarchical Inheritance

In hierarchical inheritance, multiple classes inherit from a single superclass.


Example:

python

Copy code

class Animal:

def speak(self):

return "Animal sound"

class Dog(Animal):

def speak(self):

return "Woof!"

class Cat(Animal):

def speak(self):

return "Meow!"

# Usage

dog = Dog()

cat = Cat()

print(dog.speak()) # Output: Woof!

print(cat.speak()) # Output: Meow!

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. It can sometimes lead to
complex scenarios, especially with multiple inheritance.

Example:

python

Copy code

class Flyer:

def fly(self):

return "Flying"
class Swimmer:

def swim(self):

return "Swimming"

class Animal:

def eat(self):

return "Eating"

class Duck(Flyer, Swimmer, Animal):

def quack(self):

return "Quack!"

# Usage

duck = Duck()

print(duck.fly()) # Output: Flying

print(duck.swim()) # Output: Swimming

print(duck.eat()) # Output: Eating

print(duck.quack()) # Output: Quack!

6. Abstract Inheritance

Abstract inheritance involves creating an abstract base class with abstract methods that must be
implemented by subclasses. Python uses the abc module for this.

Example:

python

Copy code

from abc import ABC, abstractmethod

class AbstractAnimal(ABC):

@abstractmethod

def speak(self):

pass
class Dog(AbstractAnimal):

def speak(self):

return "Woof!"

class Cat(AbstractAnimal):

def speak(self):

return "Meow!"

# Usage

dog = Dog()

cat = Cat()

print(dog.speak()) # Output: Woof!

print(cat.speak()) # Output: Meow!

Explanation of Key Concepts:

 Single Inheritance: Simplest form where one class inherits from one superclass.

 Multiple Inheritance: Allows a class to inherit from multiple superclasses.

 Multilevel Inheritance: Involves a chain of inheritance.

 Hierarchical Inheritance: Multiple classes inherit from a single superclass.

 Hybrid Inheritance: Combination of different inheritance types, which can be complex.

 Abstract Inheritance: Uses abstract base classes to define a common interface for
subclasses.

These types of inheritance help in organizing and structuring code in a flexible and reusable way.

exception handling

Exception handling in Python is used to manage errors and exceptions that occur during the
execution of a program. It allows you to handle errors gracefully without crashing the program.
Python uses try, except, else, and finally blocks to handle exceptions.

Basic Syntax
python

Copy code

try:

# Code that may raise an exception

pass

except ExceptionType as e:

# Code that runs if an exception occurs

pass

else:

# Code that runs if no exceptions occur

pass

finally:

# Code that always runs, regardless of whether an exception occurred

pass

Examples

1. Basic Exception Handling

python

Copy code

try:

result = 10 / 0

except ZeroDivisionError:

print("You can't divide by zero!")

In this example, dividing by zero raises a ZeroDivisionError, which is caught and handled by the
except block.

2. Handling Multiple Exceptions

python

Copy code

try:

result = int("string")

except ValueError:

print("ValueError: Invalid conversion from string to integer.")


except ZeroDivisionError:

print("You can't divide by zero!")

Here, ValueError and ZeroDivisionError are handled separately. If an exception is raised, the
corresponding except block executes.

3. Using else

python

Copy code

try:

result = 10 / 2

except ZeroDivisionError:

print("You can't divide by zero!")

else:

print("Division successful! Result:", result)

The else block runs if no exceptions are raised in the try block.

4. Using finally

python

Copy code

try:

file = open('example.txt', 'r')

content = file.read()

except FileNotFoundError:

print("File not found.")

finally:

file.close()

print("File has been closed.")

The finally block runs regardless of whether an exception occurred or not. It’s commonly used for
cleanup actions.

5. Catching All Exceptions

python

Copy code

try:

result = 10 / 0
except Exception as e:

print(f"An error occurred: {e}")

Using Exception will catch all exceptions that inherit from the base Exception class. Be cautious with
this approach, as it may catch unintended exceptions.

6. Raising Exceptions

You can also raise exceptions manually using the raise keyword.

python

Copy code

def divide(a, b):

if b == 0:

raise ValueError("The denominator cannot be zero.")

return a / b

try:

result = divide(10, 0)

except ValueError as e:

print(e)

Key Points

 try Block: Code that might cause an exception is placed here.

 except Block: Code to handle the exception if it occurs. You can specify multiple except
blocks for different exceptions.

 else Block: Code that runs if no exceptions are raised.

 finally Block: Code that runs no matter what, often used for cleanup actions like closing files.

Effective exception handling can improve the robustness and user-friendliness of your programs by
managing errors gracefully and providing meaningful feedback.

4o mini

python exception handling sample program

Sure! Here’s a sample Python program that demonstrates various aspects of exception handling:

Example: File Processing


This program attempts to read a file, process its content, and handle various potential exceptions.

python

Copy code

def read_file(file_path):

try:

# Attempt to open and read the file

with open(file_path, 'r') as file:

content = file.read()

print("File content:")

print(content)

except FileNotFoundError:

# Handle the case where the file does not exist

print(f"Error: The file '{file_path}' was not found.")

except IOError:

# Handle other I/O errors (e.g., permission issues)

print(f"Error: Could not read the file '{file_path}'.")

else:

# This block runs if no exceptions were raised

print("File read successfully.")

finally:

# This block always runs, regardless of exceptions

print("Execution of the read_file function is complete.")

def main():

file_path = "example.txt" # Change this to a valid file path for testing

read_file(file_path)

if __name__ == "__main__":

main()

Explanation

1. try Block:
o The try block contains code that may raise exceptions, such as opening and reading a
file.

2. except Blocks:

o FileNotFoundError: Catches the exception if the file specified does not exist.

o IOError: Catches general I/O errors, such as issues with file permissions.

3. else Block:

o The else block executes if no exceptions are raised in the try block. It indicates that
the file was read successfully.

4. finally Block:

o The finally block always executes, regardless of whether an exception was raised or
not. It is typically used for cleanup actions, but in this case, it just prints a completion
message.

Running the Program

1. Create a file named example.txt (or another name you provide) with some content to test
successful file reading.

2. Run the program. If the file exists, it will print the content and the success message. If the
file does not exist or another I/O error occurs, it will handle the error and print the
corresponding error message.

This sample program illustrates how to handle file operations robustly and manage various
exceptions that might occur during file processing.

4o mini

Python MCQ With Answers


Sample Python MCQs

1. What is the output of print(2 ** 3)?

o A) 6

o B) 8

o C) 9

o D) 10

Answer: B) 8

2. Which of the following is a mutable data type in Python?

o A) tuple

o B) string
o C) list

o D) int

Answer: C) list

3. What is the result of len("Python")?

o A) 5

o B) 6

o C) 7

o D) 8

Answer: B) 6

4. Which method can be used to remove whitespace from both ends of a string?

o A) strip()

o B) trim()

o C) remove()

o D) delete()

Answer: A) strip()

5. What is the output of type([])?

o A) list

o B) tuple

o C) dict

o D) set

Answer: A) list

6. Which of the following is used to define a function in Python?

o A) func

o B) define

o C) function

o D) def

Answer: D) def

7. What does the break statement do in a loop?

o A) Skips the current iteration

o B) Exits the loop

o C) Continues to the next iteration


o D) None of the above

Answer: B) Exits the loop

8. How can you create a new dictionary in Python?

o A) dict = {}

o B) dict = []

o C) dict = ()

o D) dict = set()

**Answer: A) dict = {}`

9. What will print(3 == 3.0) output?

o A) True

o B) False

o C) Error

o D) None

Answer: A) True

10. Which of the following is used to handle exceptions in Python?

o A) handle

o B) try

o C) catch

o D) except

Answer: B) try

11. How do you concatenate two strings in Python?

o A) +

o B) -

o C) *

o D) &

Answer: A) +

12. What is the default value of max() function if no arguments are provided?

o A) 0

o B) None

o C) -1

o D) Inf
Answer: B) None

13. Which method is used to add an element to the end of a list?

o A) add()

o B) append()

o C) insert()

o D) extend()

Answer: B) append()

14. What does the pass statement do?

o A) Exits the loop

o B) Passes the current iteration

o C) Does nothing

o D) Continues to the next iteration

Answer: C) Does nothing

15. Which of the following operators is used for floor division in Python?

o A) /

o B) %

o C) //

o D) ^

Answer: C) //

16. What will print(2 * 3 == 6) output?

o A) True

o B) False

o C) Error

o D) None

Answer: A) True

17. How do you comment a single line in Python?

o A) //

o B) /*

o C) #

o D) --

Answer: C) #
18. Which data type is immutable in Python?

o A) list

o B) dict

o C) set

o D) tuple

Answer: D) tuple

19. Which function is used to get the length of a list?

o A) length()

o B) size()

o C) len()

o D) count()

Answer: C) len()

20. What is the result of 3 / 2 in Python 3.x?

o A) 1

o B) 1.5

o C) 1.0

o D) 2

Answer: B) 1.5

Feel free to adjust or expand on these questions as needed. If you need more questions or specific
topics covered, just let me know!

4o mini

Advanced Python questions?

Certainly! Here are some advanced Python multiple-choice questions that cover topics like
decorators, context managers, metaclasses, concurrency, and more.

Advanced Python MCQs

1. What is the primary purpose of a Python decorator?

o A) To modify the behavior of a function or method

o B) To create a new class


o C) To handle exceptions

o D) To create a thread

Answer: A) To modify the behavior of a function or method

2. What is the purpose of the __enter__ and __exit__ methods in Python?

o A) To define a new class

o B) To handle exceptions

o C) To implement a context manager

o D) To create a new thread

Answer: C) To implement a context manager

3. Which of the following statements is true about Python's Global Interpreter Lock (GIL)?

o A) It allows multiple threads to run in parallel on multiple CPU cores

o B) It prevents Python programs from utilizing multiple CPU cores effectively

o C) It is used to manage memory allocation

o D) It handles the allocation of network resources

Answer: B) It prevents Python programs from utilizing multiple CPU cores effectively

4. How do you define a metaclass in Python?

o A) By creating a class that inherits from type

o B) By using the @metaclass decorator

o C) By defining a class inside another class

o D) By using the class keyword only

Answer: A) By creating a class that inherits from type

5. What is the output of list(map(lambda x: x * 2, [1, 2, 3]))?

o A) [2, 4, 6]

o B) [1, 2, 3]

o C) [2, 4, 6, 8]

o D) None

Answer: A) [2, 4, 6]

6. What does the __call__ method do in a Python class?

o A) Allows an instance of the class to be called as a function

o B) Calls a method from a superclass

o C) Calls a method on a specific instance


o D) Defines the constructor of a class

Answer: A) Allows an instance of the class to be called as a function

7. Which of the following is the correct way to define a class method?

o A) @classmethod

o B) @staticmethod

o C) @property

o D) @method

Answer: A) @classmethod

8. What is the result of executing the following code?

python

Copy code

def func(a, b=[]):

b.append(a)

return b

print(func(1))

print(func(2, []))

print(func(3))

o A) [1], [2], [3]

o B) [1], [2], [1, 3]

o C) [1], [2], [2, 3]

o D) [1], [2], [3]

Answer: B) [1], [2], [1, 3]

9. Which Python module provides support for asynchronous programming?

o A) asyncio

o B) threading

o C) multiprocessing

o D) concurrent

Answer: A) asyncio

10. What is the purpose of the __new__ method in Python?

o A) To initialize the class


o B) To create a new instance of a class

o C) To modify the class attributes

o D) To define a new class attribute

Answer: B) To create a new instance of a class

11. How do you create a generator function in Python?

o A) By using the yield keyword

o B) By using the return keyword

o C) By using the async keyword

o D) By using the def keyword only

Answer: A) By using the yield keyword

12. Which of the following statements is correct about Python's super() function?

o A) It is used to call a method from a superclass

o B) It creates a new instance of a class

o C) It modifies the class attributes

o D) It defines a new method in the class

Answer: A) It is used to call a method from a superclass

13. What is the output of set([1, 2, 2, 3, 4])?

o A) [1, 2, 3, 4]

o B) (1, 2, 3, 4)

o C) {1, 2, 3, 4}

o D) {1, 2, 2, 3, 4}

Answer: C) {1, 2, 3, 4}

14. What is the purpose of the __slots__ attribute in Python classes?

o A) To restrict the attributes that an instance can have

o B) To define new methods for a class

o C) To manage the class's memory

o D) To initialize the class attributes

Answer: A) To restrict the attributes that an instance can have

15. Which function can be used to obtain the type of an object?

o A) type()

o B) id()
o C) object()

o D) class()

Answer: A) type()

16. What is the output of the following code?

python

Copy code

class A:

def __init__(self):

self.value = 10

class B(A):

def __init__(self):

super().__init__()

self.value = 20

obj = B()

print(obj.value)

o A) 10

o B) 20

o C) None

o D) Error

Answer: B) 20

17. What is the use of the @property decorator in Python?

o A) To create a getter method

o B) To create a setter method

o C) To define a method that behaves like an attribute

o D) To handle exceptions

Answer: C) To define a method that behaves like an attribute

18. Which of the following is true about Python's assert statement?

o A) It is used to perform debugging checks

o B) It is used to handle exceptions


o C) It is used to define a class method

o D) It is used to create a new instance of a class

Answer: A) It is used to perform debugging checks

19. Which method is used to serialize a Python object into JSON format?

o A) json.dump()

o B) json.load()

o C) json.dumps()

o D) json.loads()

Answer: C) json.dumps()

20. What is the output of the following code?

python

Copy code

def outer():

x = 10

def inner():

nonlocal x

x = 20

inner()

return x

print(outer())

o A) 10

o B) 20

o C) None

o D) Error

Answer: B) 20
Lists

1. How do you create a list in Python?

o A) []

o B) ()

o C) {}

o D) <>

Answer: A) []

2. What will list(range(5)) return?

o A) [1, 2, 3, 4, 5]

o B) [0, 1, 2, 3, 4]

o C) [0, 1, 2, 3, 4, 5]

o D) range(5)

Answer: B) [0, 1, 2, 3, 4]

3. How do you access the third element of a list my_list?

o A) my_list[2]

o B) my_list[3]

o C) my_list.get(3)

o D) my_list[1]

Answer: A) my_list[2]

4. Which method is used to remove the last item from a list?

o A) pop()

o B) remove()

o C) del()

o D) discard()

Answer: A) pop()

5. What is the result of len([1, 2, [3, 4]])?

o A) 3

o B) 4

o C) 2

o D) 5
Answer: A) 3

6. How do you concatenate two lists a and b?

o A) a + b

o B) a.append(b)

o C) a.extend(b)

o D) a.concat(b)

Answer: A) a + b

7. What does my_list.clear() do?

o A) Removes all items from the list

o B) Clears the first item

o C) Clears the last item

o D) Sets the list to None

Answer: A) Removes all items from the list

8. How do you sort a list in Python?

o A) my_list.sort()

o B) sort(my_list)

o C) my_list.order()

o D) my_list.sorted()

Answer: A) my_list.sort()

9. What is the result of [1, 2, 3] * 2?

o A) [1, 2, 3, 1, 2, 3]

o B) [2, 4, 6]

o C) [1, 2, 3, 2, 4, 6]

o D) [1, 2, 3, 4, 5, 6]

Answer: A) [1, 2, 3, 1, 2, 3]

10. How do you insert an item into a list at a specific position?

o A) my_list.insert(index, item)

o B) my_list.add(index, item)

o C) my_list.append(index, item)

o D) my_list.add(item, index)

Answer: A) my_list.insert(index, item)


Tuples

11. How do you create a tuple in Python?

o A) ()

o B) []

o C) {}

o D) <>

Answer: A) ()

12. What will len((1, 2, 3)) return?

o A) 2

o B) 3

o C) 4

o D) None

Answer: B) 3

13. Can you modify elements of a tuple?

o A) Yes

o B) No

o C) Only if the tuple is empty

o D) Only if the tuple contains one element

Answer: B) No

14. How do you access the first element of a tuple my_tuple?

o A) my_tuple[0]

o B) my_tuple[1]

o C) my_tuple.get(0)

o D) my_tuple.first()

Answer: A) my_tuple[0]

15. Which method is used to convert a list to a tuple?

o A) tuple(list)

o B) list.to_tuple()

o C) tuple.convert()

o D) convert(tuple)

Answer: A) tuple(list)
16. What will (1, 2) + (3, 4) result in?

o A) (1, 2, 3, 4)

o B) (1, 2, (3, 4))

o C) (1, 2) * (3, 4)

o D) (1, 2, 3, 4, 3, 4)

Answer: A) (1, 2, 3, 4)

17. How do you count the occurrences of an element in a tuple?

o A) my_tuple.count(item)

o B) my_tuple.frequency(item)

o C) my_tuple.occurrences(item)

o D) my_tuple.find(item)

Answer: A) my_tuple.count(item)

18. How do you find the index of an element in a tuple?

o A) my_tuple.index(item)

o B) my_tuple.find(item)

o C) my_tuple.locate(item)

o D) my_tuple.position(item)

Answer: A) my_tuple.index(item)

19. Can a tuple contain other tuples?

o A) Yes

o B) No

o C) Only if they are nested

o D) Only if they are empty

Answer: A) Yes

20. What will (1, 2, 3)[1:2] return?

o A) (2,)

o B) (2, 3)

o C) 2

o D) (1, 2)

Answer: A) (2,)

Sets
21. How do you create a set in Python?

o A) set()

o B) []

o C) {}

o D) ()

Answer: A) set()

22. What is the output of set([1, 2, 2, 3])?

o A) {1, 2, 3}

o B) [1, 2, 3]

o C) (1, 2, 3)

o D) {1, 2, 2, 3}

Answer: A) {1, 2, 3}

23. How do you add an element to a set?

o A) my_set.add(element)

o B) my_set.insert(element)

o C) my_set.append(element)

o D) my_set.put(element)

Answer: A) my_set.add(element)

24. What does my_set.remove(element) do?

o A) Removes the specified element from the set

o B) Removes all elements from the set

o C) Clears the set

o D) Adds the element to the set

Answer: A) Removes the specified element from the set

25. What is the result of len(set([1, 2, 3, 4, 4]))?

o A) 5

o B) 4

o C) 3

o D) 2

Answer: B) 4

26. How do you find the intersection of two sets a and b?


o A) a & b

o B) a.intersection(b)

o C) a.intersect(b)

o D) Both A and B

Answer: D) Both A and B

27. What is the result of a - b where a and b are sets?

o A) The elements in a not in b

o B) The elements in b not in a

o C) The union of a and b

o D) The intersection of a and b

Answer: A) The elements in a not in b

28. How do you create a set with elements from another set?

o A) set(a)

o B) a.copy()

o C) a.clone()

o D) set.copy(a)

Answer: A) set(a)

29. Which method removes and returns an arbitrary element from a set?

o A) pop()

o B) remove()

o C) discard()

o D) delete()

Answer: A) pop()

30. Can a set contain mutable elements?

o A) Yes

o B) No

o C) Only if they are lists

o D) Only if they are tuples

Answer: B) No

Dictionaries

31. How do you create a dictionary in Python?


o A) {}

o B) []

o C) ()

o D) <>

Answer: A) {}

32. How do you access a value in a dictionary my_dict?

o A) my_dict[key]

o B) my_dict.get(key)

o C) my_dict[key].value

o D) Both A and B

Answer: D) Both A and B

33. Which method is used to add or update a key-value pair in a dictionary?

o A) my_dict.update(key, value)

o B) my_dict.add(key, value)

o C) my_dict[key] = value

o D) my_dict.set(key, value)

Answer: C) my_dict[key] = value

34. What does my_dict.pop(key) do?

o A) Removes the key-value pair and returns the value

o B) Removes the key but keeps the value

o C) Updates the value of the key

o D) Adds a new key-value pair

Answer: A) Removes the key-value pair and returns the value

35. How do you get all keys from a dictionary?

o A) my_dict.keys()

o B) my_dict.get_keys()

o C) my_dict.all_keys()

o D) my_dict.list_keys()

Answer: A) my_dict.keys()

36. How do you get all values from a dictionary?

o A) my_dict.values()
o B) my_dict.get_values()

o C) my_dict.all_values()

o D) my_dict.list_values()

Answer: A) my_dict.values()

37. Which method is used to remove all items from a dictionary?

o A) my_dict.clear()

o B) my_dict.delete()

o C) my_dict.remove()

o D) my_dict.discard()

Answer: A) my_dict.clear()

38. What will my_dict.items() return?

o A) A list of tuples containing key-value pairs

o B) A dictionary containing only keys

o C) A dictionary containing only values

o D) A list of keys

Answer: A) A list of tuples containing key-value pairs

39. How do you check if a key exists in a dictionary?

o A) key in my_dict

o B) my_dict.has_key(key)

o C) my_dict.contains(key)

o D) key.exists(my_dict)

Answer: A) key in my_dict

40. Can dictionary keys be mutable objects?

o A) Yes

o B) No

o C) Only if they are integers

o D) Only if they are strings

Answer: B) No

Advanced Questions

41. What will my_list[::2] return for my_list = [1, 2, 3, 4, 5]?

o A) [1, 3, 5]
o B) [2, 4]

o C) [1, 2, 3]

o D) [2, 3, 4]

Answer: A) [1, 3, 5]

42. Which function is used to create a tuple with a single element?

o A) tuple(element)

o B) tuple((element,))

o C) tuple([element])

o D) tuple.add(element)

Answer: B) tuple((element,))

43. How do you get the union of two sets a and b?

o A) a | b

o B) a.union(b)

o C) a + b

o D) Both A and B

Answer: D) Both A and B

44. What is the result of my_set.update({1, 2, 3})?

o A) Adds elements from {1, 2, 3} to my_set

o B) Removes all elements from my_set

o C) Creates a new set with elements {1, 2, 3}

o D) Updates my_set to be {1, 2, 3}

Answer: A) Adds elements from {1, 2, 3} to my_set

45. Which method removes a specified element from a set if it exists, without raising an error
if it does not?

o A) discard()

o B) remove()

o C) pop()

o D) delete()

Answer: A) discard()

46. What is the output of dict(zip(['a', 'b'], [1, 2]))?

o A) {'a': 1, 'b': 2}
o B) {'a': 1, 'b': 1}

o C) [(a, 1), (b, 2)]

o D) [['a', 1], ['b', 2]]

Answer: A) {'a': 1, 'b': 2}

47. Which method can be used to merge two dictionaries in Python 3.9 and above?

o A) dict1 | dict2

o B) dict1.update(dict2)

o C) dict1.merge(dict2)

o D) dict1.concat(dict2)

Answer: A) dict1 | dict2

48. How do you get the value associated with a key, or a default value if the key is not present
in a dictionary?

o A) my_dict.get(key, default)

o B) my_dict.fetch(key, default)

o C) my_dict.value(key, default)

o D) my_dict.default(key, default)

Answer: A) my_dict.get(key, default)

49. Which method returns a view object that displays a list of all the keys in a dictionary?

o A) keys()

o B) values()

o C) items()

o D) view()

Answer: A) keys()

50. How can you remove a key-value pair from a dictionary while also getting the value?

o A) pop()

o B) remove()

o C) discard()

o D) del()

Answer: A) pop()

51. What will set([1, 1, 2, 2, 3]) - {2, 3} result in?

o A) {1}
o B) {1, 2, 3}

o C) {2}

o D) {1, 2}

Answer: A) {1}

52. Which method is used to create a shallow copy of a dictionary?

o A) copy()

o B) clone()

o C) duplicate()

o D) new()

Answer: A) copy()

53. How do you get the unique elements from a list using a set?

o A) set(my_list)

o B) list(set(my_list))

o C) unique(my_list)

o D) my_list.unique()

Answer: B) list(set(my_list))

54. How do you create a dictionary with default values for new keys?

o A) defaultdict

o B) default_dict

o C) dict_default

o D) default_values

Answer: A) defaultdict

55. What is the output of tuple([1, 2, 3] * 2)?

o A) (1, 2, 3, 1, 2, 3)

o B) [1, 2, 3, 1, 2, 3]

o C) (1, 2, 3) * 2

o D) [1, 2] * 3

Answer: A) (1, 2, 3, 1, 2, 3)

56. Which method removes an item from a set and returns it?

o A) pop()

o B) remove()
o C) discard()

o D) delete()

Answer: A) pop()

57. How do you check if a dictionary is empty?

o A) not my_dict

o B) my_dict.empty()

o C) len(my_dict) == 0

o D) my_dict.is_empty()

Answer: A) not my_dict

58. What is the result of a.add(b) where a is a set and b is a tuple?

o A) Raises a TypeError

o B) Adds b as a single element in a

o C) Merges a and b

o D) Both A and B

Answer: B) Adds b as a single element in a

59. How do you get a list of tuples from a dictionary?

o A) my_dict.items()

o B) my_dict.to_list()

o C) list(my_dict)

o D) dict.list_items()

Answer: A) my_dict.items()

60. How do you get the first element of a tuple my_tuple?

o A) my_tuple[0]

o B) my_tuple.first()

o C) my_tuple[1]

o D) my_tuple.get(0)

Answer: A) my_tuple[0]

61. Which method is used to remove all occurrences of an item from a set?

o A) discard()

o B) remove()

o C) clear()
o D) delete()

Answer: A) discard()

62. What will set("hello") return?

o A) {'h', 'e', 'l', 'o'}

o B) {'hello'}

o C) {'h': 1, 'e': 1, 'l': 2, 'o': 1}

o D) {'h': 1, 'e': 1, 'l': 2}

Answer: A) {'h', 'e', 'l', 'o'}

63. How do you get a view of all the values in a dictionary?

o A) my_dict.values()

o B) my_dict.all_values()

o C) my_dict.view_values()

o D) my_dict.get_values()

Answer: A) my_dict.values()

64. What is the result of my_dict.setdefault('key', 'default')?

o A) Returns the value of 'key', setting it to 'default' if it doesn't exist

o B) Sets 'key' to 'default' and returns 'default'

o C) Sets 'key' to 'default' and returns the previous value

o D) Returns 'default' if 'key' exists

Answer: A) Returns the value of 'key', setting it to 'default' if it doesn't exist

65. How do you remove a dictionary entry by key?

o A) del my_dict[key]

o B) my_dict.remove(key)

o C) my_dict.pop(key)

o D) Both A and C

Answer: D) Both A and C

66. How do you get the number of elements in a set?

o A) len(set)

o B) count(set)

o C) size(set)

o D) len(set)
Answer: A) len(set)

67. What will set('hello').pop() return?

o A) An arbitrary character from 'hello'

o B) The string 'hello'

o C) A set of characters

o D) None

Answer: A) An arbitrary character from 'hello'

68. How do you create a dictionary with default values for new keys using defaultdict?

o A) defaultdict(default_factory)

o B) dict.default(default_factory)

o C) defaultdict(key, default_factory)

o D) defaultdict.default_factory()

Answer: A) defaultdict(default_factory)

69. What will my_tuple[::-1] return for my_tuple = (1, 2, 3, 4)?

o A) (4, 3, 2, 1)

o B) (1, 2, 3, 4)

o C) (2, 3, 4)

o D) (3, 4)

Answer: A) (4, 3, 2, 1)

70. Which method is used to return the set of differences between two sets?

o A) difference()

o B) subtract()

o C) diff()

o D) remove()

Answer: A) difference()

71. How do you get the dictionary of all items (key-value pairs) in a dictionary?

o A) items()

o B) dict()

o C) get_items()

o D) all_items()

Answer: A) items()
72. What does the dict.fromkeys(seq, value) method do?

o A) Creates a new dictionary with keys from seq and value as their value

o B) Creates a new dictionary with value as keys and seq as their value

o C) Updates dict with keys from seq and value as their value

o D) Converts seq to a dictionary with default values

Answer: A) Creates a new dictionary with keys from seq and value as their value

73. Which set operation returns a new set with elements that are only in one of the sets?

o A) symmetric_difference()

o B) exclusive()

o C) only_in_one()

o D) unique()

Answer: A) symmetric_difference()

74. What is the output of list(set([1, 2, 2, 3, 4]))?

o A) [1, 2, 3, 4]

o B) [1, 2, 4]

o C) [1, 3, 2, 4]

o D) [2, 3, 4]

Answer: A) [1, 2, 3, 4]

75. Which method would you use to add multiple items to a set?

o A) update()

o B) add_all()

o C) insert()

o D) merge()

Answer: A) update()

76. How do you remove an element from a set without raising an error if the element does not
exist?

o A) discard()

o B) remove()

o C) pop()

o D) delete()

Answer: A) discard()
77. What is the output of my_dict.get('key', 'default') if 'key' does not exist in my_dict?

o A) 'default'

o B) None

o C) 'key'

o D) Error

Answer: A) 'default'

78. How can you create a dictionary from a list of tuples?

o A) dict(list_of_tuples)

o B) dict.from_tuples(list_of_tuples)

o C) list_to_dict(list_of_tuples)

o D) dict.convert(list_of_tuples)

Answer: A) dict(list_of_tuples)

79. What does dict.popitem() do?

o A) Removes and returns an arbitrary key-value pair

o B) Removes and returns the first key-value pair

o C) Removes a specified key-value pair

o D) Returns a list of all key-value pairs

Answer: A) Removes and returns an arbitrary key-value pair

80. How do you create a tuple with repeated elements?

o A) (element,) * n

o B) (element * n)

o C) repeat(element, n)

o D) tuple.repeat(element, n)

Answer: A) (element,) * n

81. How can you update a dictionary with another dictionary?

o A) my_dict.update(another_dict)

o B) my_dict.add(another_dict)

o C) my_dict.merge(another_dict)

o D) my_dict.concat(another_dict)

Answer: A) my_dict.update(another_dict)

82. Which method is used to find the intersection of two sets?


o A) intersection()

o B) common()

o C) shared()

o D) overlap()

Answer: A) intersection()

83. What does dict.pop('key', 'default') do?

o A) Removes and returns the value of 'key', or 'default' if 'key' does not exist

o B) Returns 'key' if it exists, otherwise 'default'

o C) Removes 'key' and sets 'default' as its value

o D) Sets 'default' as the value of 'key'

Answer: A) Removes and returns the value of 'key', or 'default' if 'key' does not exist

84. How do you create a set with elements from a list?

o A) set(list)

o B) list.set()

o C) set.add(list)

o D) create_set(list)

Answer: A) set(list)

85. Which method is used to return the union of two sets?

o A) union()

o B) add()

o C) combine()

o D) merge()

Answer: A) union()

86. What will tuple([1, 2, 3] * 2) return?

o A) (1, 2, 3, 1, 2, 3)

o B) [1, 2, 3, 1, 2, 3]

o C) (1, 2, 3) * 2

o D) [1, 2] * 3

Answer: A) (1, 2, 3, 1, 2, 3)

87. How do you find the difference between two sets?

o A) difference()
o B) subtract()

o C) remove()

o D) unique()

Answer: A) difference()

88. How do you get the keys from a dictionary?

o A) my_dict.keys()

o B) my_dict.get_keys()

o C) my_dict.all_keys()

o D) my_dict.list_keys()

Answer: A) my_dict.keys()

89. What will my_set.intersection(other_set) return?

o A) A set with elements that are in both my_set and other_set

o B) A set with elements that are in my_set but not in other_set

o C) A set with elements that are in either my_set or other_set

o D) A set with elements that are in my_set but not in other_set and vice versa

Answer: A) A set with elements that are in both my_set and other_set

90. What does the dict.items() method return?

o A) A view of the dictionary’s key-value pairs

o B) A list of dictionary keys

o C) A list of dictionary values

o D) A view of the dictionary’s values

Answer: A) A view of the dictionary’s key-value pairs

91. How do you create a set with elements from a string?

o A) set(string)

o B) list(string)

o C) create_set(string)

o D) string.to_set()

Answer: A) set(string)

92. What does dict.get(key, default) do if the key exists in the dictionary?

o A) Returns the value associated with the key

o B) Returns the default value


o C) Sets the key to the default value

o D) Returns the key

Answer: A) Returns the value associated with the key

93. How do you remove all elements from a set?

o A) clear()

o B) remove_all()

o C) delete()

o D) discard_all()

Answer: A) clear()

94. How do you get the difference between two dictionaries?

o A) dict1.keys() - dict2.keys()

o B) dict1.items() - dict2.items()

o C) dict1.difference(dict2)

o D) dict1 - dict2

Answer: B) dict1.items() - dict2.items()

95. How do you create a set from a list with unique elements?

o A) set(list)

o B) unique(list)

o C) list.set()

o D) create_set(list)

Answer: A) set(list)

96. What will my_dict.setdefault('key', 'default') do if 'key' already exists in my_dict?

o A) Returns the value of 'key'

o B) Sets 'key' to 'default'

o C) Returns 'default'

o D) Updates 'key' to 'default'

Answer: A) Returns the value of 'key'

97. How do you get the values of a dictionary as a list?

o A) list(my_dict.values())

o B) my_dict.values().to_list()

o C) my_dict.get_values()
o D) list.from_values(my_dict)

Answer: A) list(my_dict.values())

98. How do you create a set with elements from a range?

o A) set(range())

o B) range.to_set()

o C) list(range())

o D) create_set(range())

Answer: A) set(range())

99. What does dict.update(other_dict) do?

o A) Updates the dictionary with elements from other_dict

o B) Replaces dict with other_dict

o C) Adds other_dict to dict

o D) Merges dict and other_dict

Answer: A) Updates the dictionary with elements from other_dict

100. How do you remove and return the last item of a dictionary? –

A) popitem()

B) remove_last()

C) pop_last()

D) last()

Data Types

1. Which of the following is a mutable data type in Python?

o A) int

o B) str

o C) tuple

o D) list

Answer: D) list

2. What is the output of type(5.0)?

o A) <class 'int'>

o B) <class 'float'>
o C) <class 'str'>

o D) <class 'complex'>

Answer: B) <class 'float'>

3. Which of the following is used to create a dictionary in Python?

o A) []

o B) {}

o C) ()

o D) <>

Answer: B) {}

4. What will len("hello") return?

o A) 4

o B) 5

o C) 6

o D) None

Answer: B) 5

5. Which method converts a string to a list of characters?

o A) list()

o B) str()

o C) split()

o D) to_list()

Answer: A) list()

6. How do you convert a list to a tuple?

o A) tuple(list)

o B) list(tuple)

o C) convert(list)

o D) to_tuple(list)

Answer: A) tuple(list)

7. What is the result of bool([])?

o A) True

o B) False

o C) None
o D) 0

Answer: B) False

8. How do you create an empty set in Python?

o A) {}

o B) set()

o C) []

o D) empty_set()

Answer: B) set()

9. Which method is used to add an item to a list?

o A) append()

o B) add()

o C) insert()

o D) extend()

Answer: A) append()

10. What is the result of 3**2?

o A) 6

o B) 9

o C) 27

o D) None

Answer: B) 9

Operators

11. Which operator is used for integer division in Python?

o A) /

o B) %

o C) //

o D) **

Answer: C) //

12. What does the not operator do in Python?

o A) Negates a boolean value

o B) Performs a bitwise NOT operation

o C) Reverses the order of items


o D) None of the above

Answer: A) Negates a boolean value

13. What is the output of 5 % 2?

o A) 2

o B) 1

o C) 0

o D) 5

Answer: B) 1

14. Which operator is used to check if two values are not equal?

o A) ==

o B) !=

o C) >

o D) <

Answer: B) !=

15. What is the result of 3 + 2 * 2?

o A) 10

o B) 7

o C) 12

o D) 8

Answer: B) 7

16. What does a and b evaluate to if a is True and b is False?

o A) True

o B) False

o C) None

o D) Error

Answer: B) False

17. What is the output of 5 == 5.0?

o A) True

o B) False

o C) None

o D) Error
Answer: A) True

18. Which operator is used for membership testing?

o A) in

o B) is

o C) not

o D) !=

Answer: A) in

19. What is the output of 2 ** 3 ** 2?

o A) 512

o B) 64

o C) 256

o D) None

Answer: A) 512

20. What is the result of 10 // 3?

o A) 3

o B) 3.33

o C) 4

o D) 2

Answer: C) 3

Decision Making

21. Which keyword is used to start a conditional statement in Python?

o A) if

o B) elif

o C) else

o D) switch

Answer: A) if

22. How do you write an else clause after an if statement?

o A) if condition: ... else: ...

o B) if condition then: ... else ...

o C) if condition then ... else ...

o D) if condition: ... elseif: ... else: ...


Answer: A) if condition: ... else: ...

23. Which keyword is used to handle multiple conditions in an if statement?

o A) elif

o B) or

o C) and

o D) else

Answer: A) elif

24. What does the following code return: x = 5; y = 10; print(x > y)?

o A) True

o B) False

o C) None

o D) Error

Answer: B) False

25. How do you check if a variable x is between 5 and 10, inclusive?

o A) 5 <= x <= 10

o B) x in (5, 10)

o C) x > 5 and x < 10

o D) x >= 5 and x <= 10

Answer: A) 5 <= x <= 10

26. What will be the output of the following code? x = 3; if x > 2: print("yes") else: print("no")

o A) yes

o B) no

o C) None

o D) Error

Answer: A) yes

27. Which statement is used to exit a loop prematurely?

o A) continue

o B) break

o C) exit

o D) stop

Answer: B) break
28. What does the continue statement do in a loop?

o A) Exits the loop

o B) Skips the rest of the loop iteration

o C) Restarts the loop

o D) None of the above

Answer: B) Skips the rest of the loop iteration

29. How do you check if a condition is false using a conditional statement?

o A) if not condition: ...

o B) if condition == False: ...

o C) if !condition: ...

o D) if condition: ... else: ...

Answer: A) if not condition: ...

30. Which of the following will evaluate to True?

o A) 0 == False

o B) None == False

o C) 1 == True

o D) [] == True

Answer: C) 1 == True

Looping

31. Which loop is used to iterate over a sequence in Python?

o A) for

o B) while

o C) do-while

o D) repeat

Answer: A) for

32. How do you iterate over a list my_list using a for loop?

o A) for item in my_list:

o B) for item of my_list:

o C) for each item in my_list:

o D) for item: my_list

Answer: A) for item in my_list:


33. What is the output of the following code? for i in range(3): print(i)

o A) 0 1 2

o B) 1 2 3

o C) 0 1 2 3

o D) 1 2

Answer: A) 0 1 2

34. What is the purpose of the range() function in a loop?

o A) Generates a sequence of numbers

o B) Defines a loop condition

o C) Stores loop results

o D) Controls loop exit

Answer: A) Generates a sequence of numbers

35. How can you ensure a loop executes at least once?

o A) Use a while True loop with a break statement

o B) Use a for loop with a condition

o C) Use a while loop with an initial True condition

o D) All of the above

Answer: A) Use a while True loop with a break statement

36. What is the output of the following code? i = 1; while i < 4: print(i); i += 1

o A) 1 2 3

o B) 1 2 3 4

o C) 1 2

o D) 1 2 3 4 5

Answer: A) 1 2 3

37. How do you stop a while loop from executing?

o A) break

o B) continue

o C) exit

o D) stop

Answer: A) break

38. Which of the following is the correct way to use break in a loop?
o A) for i in range(10): if condition: break

o B) while condition: if break: ...

o C) if condition: break

o D) for i in range(10): break if condition

Answer: A) for i in range(10): if condition: break

39. How do you create an infinite loop in Python?

o A) while True:

o B) for i in range(0, 0):

o C) while False:

o D) for i in range(10):

Answer: A) while True:

40. Which loop will not execute if the condition is initially False?

o A) for

o B) while

o C) do-while

o D) repeat

Answer: B) while

Data Types and Operations

41. What is the output of str(10) + str(20)?

o A) 30

o B) 1020

o C) 10 20

o D) Error

Answer: B) 1020

42. What will int('123') return?

o A) 123

o B) '123'

o C) None

o D) Error

Answer: A) 123

43. Which method removes whitespace from the start and end of a string?
o A) strip()

o B) trim()

o C) clean()

o D) remove()

Answer: A) strip()

44. How do you find the length of a list?

o A) len()

o B) length()

o C) size()

o D) count()

Answer: A) len()

45. Which method is used to sort a list in Python?

o A) sort()

o B) order()

o C) arrange()

o D) list_sort()

Answer: A) sort()

46. What does list.append(item) do?

o A) Adds item to the end of the list

o B) Inserts item at the beginning of the list

o C) Removes item from the list

o D) None of the above

Answer: A) Adds item to the end of the list

47. How do you access the third element of a list my_list?

o A) my_list[2]

o B) my_list[3]

o C) my_list.get(3)

o D) my_list.third()

Answer: A) my_list[2]

48. What is the result of [1, 2] + [3, 4]?

o A) [1, 2, 3, 4]
o B) [1, 2, [3, 4]]

o C) [4, 3, 2, 1]

o D) [1, 2, 4, 3]

Answer: A) [1, 2, 3, 4]

49. How do you check if a key exists in a dictionary?

o A) key in dict

o B) dict.has_key(key)

o C) dict.contains(key)

o D) key.exists(dict)

Answer: A) key in dict

50. What does list.extend([x, y]) do?

o A) Adds elements x and y to the end of the list

o B) Adds x and y as a sublist

o C) Replaces the list with [x, y]

o D) Inserts x and y at the beginning

Answer: A) Adds elements x and y to the end of the list

Operators and Expressions

51. What will 5 + 3 * 2 evaluate to?

o A) 16

o B) 13

o C) 10

o D) 8

Answer: B) 11

52. Which operator is used to perform logical AND operation?

o A) &&

o B) &

o C) and

o D) &&

Answer: C) and

53. What does x is y check in Python?

o A) If x and y have the same value


o B) If x and y are of the same type

o C) If x and y refer to the same object

o D) If x and y are not equal

Answer: C) If x and y refer to the same object

54. What does the // operator do?

o A) Integer division

o B) Modulus operation

o C) Floating point division

o D) Exponentiation

Answer: A) Integer division

55. How do you check for equality between two variables?

o A) ==

o B) !=

o C) >

o D) is

Answer: A) ==

56. Which operator has the highest precedence?

o A) +

o B) *

o C) **

o D) //

Answer: C) **

57. What is the output of "a" * 3?

o A) aaa

o B) a a a

o C) aaaaa

o D) Error

Answer: A) aaa

58. What does the or operator do in Python?

o A) Returns True if at least one of the operands is True

o B) Returns True if both operands are True


o C) Returns False if either operand is False

o D) None of the above

Answer: A) Returns True if at least one of the operands is True

59. What is the output of 3 ** 2 ** 1?

o A) 9

o B) 81

o C) 27

o D) None

Answer: A) 9

60. Which operator is used for bitwise AND operation?

o A) &

o B) &&

o C) and

o D) |

Answer: A) &

Decision Making and Loops

61. What will be the result of the following code? x = 4; while x < 8: print(x); x += 2

o A) 4 6 8

o B) 4 6

o C) 4 6 8 10

o D) 4 6 8 10 12

Answer: B) 4 6

62. How do you execute a block of code multiple times with a for loop?

o A) for item in iterable:

o B) while condition:

o C) repeat block times:

o D) loop item in iterable:

Answer: A) for item in iterable:

63. What does the break statement do in a loop?

o A) Exits the loop

o B) Continues with the next iteration


o C) Restarts the loop

o D) Stops the program

Answer: A) Exits the loop

64. How do you create a loop that executes exactly five times?

o A) for i in range(5):

o B) while i < 5:

o C) repeat 5 times:

o D) loop 5 times:

Answer: A) for i in range(5):

65. What will be the output of for i in range(1, 4): print(i)?

o A) 1 2 3

o B) 1 2 3 4

o C) 1 2

o D) 0 1 2 3

Answer: A) 1 2 3

66. Which keyword is used to define a function in Python?

o A) function

o B) def

o C) func

o D) define

Answer: B) def

67. What is the default return value of a function that does not have a return statement?

o A) None

o B) 0

o C) False

o D) Error

Answer: A) None

68. How do you call a function named my_function with arguments 1 and 2?

o A) my_function(1, 2)

o B) my_function{1, 2}

o C) my_function[1, 2]
o D) call my_function(1, 2)

Answer: A) my_function(1, 2)

69. Which loop will always execute at least once?

o A) for

o B) while

o C) do-while

o D) repeat

Answer: C) do-while

70. What will the following code print? for i in range(2): print(i ** 2)

o A) 0 1

o B) 0 1 4

o C) 1 4

o D) 2 4

Answer: A) 0 1

Additional Questions

71. How do you handle exceptions in Python?

o A) try-except

o B) catch-finally

o C) try-catch

o D) error-handler

Answer: A) try-except

72. What is the output of print(type([]))?

o A) <class 'list'>

o B) <class 'tuple'>

o C) <class 'dict'>

o D) <class 'set'>

Answer: A) <class 'list'>

73. Which method can be used to find the maximum value in a list?

o A) max()

o B) highest()

o C) top()
o D) largest()

Answer: A) max()

74. What does the pop() method do for lists?

o A) Removes and returns the last item

o B) Adds an item to the end

o C) Returns the last item without removing

o D) Removes an item by index

Answer: A) Removes and returns the last item

75. How do you create a set containing the elements of a list?

o A) set(list)

o B) list.to_set()

o C) create_set(list)

o D) convert_to_set(list)

Answer: A) set(list)

76. What will range(3, 6) generate?

o A) 3 4 5

o B) 3 4 5 6

o C) 3 6

o D) 3 4 5 6 7

Answer: A) 3 4 5

77. What is the output of list("123")?

o A) ['1', '2', '3']

o B) [123]

o C) [1, 2, 3]

o D) ['123']

Answer: A) ['1', '2', '3']

78. Which function can be used to get the sum of all elements in a list?

o A) sum()

o B) total()

o C) add_all()

o D) accumulate()
Answer: A) sum()

79. How do you convert a string s to lowercase?

o A) s.lower()

o B) s.to_lower()

o C) s.lowercase()

o D) s.convert_to_lower()

Answer: A) s.lower()

80. What does the in operator do?

o A) Checks for membership

o B) Performs an intersection

o C) Concatenates two lists

o D) Checks for equality

Answer: A) Checks for membership

81. Which method is used to remove an item from a set?

o A) discard()

o B) remove()

o C) pop()

o D) delete()

Answer: B) remove()

82. What will tuple([1, 2, 3] * 2) return?

o A) (1, 2, 3, 1, 2, 3)

o B) [1, 2, 3, 1, 2, 3]

o C) (1, 2, 3) * 2

o D) [1, 2] * 3

Answer: A) (1, 2, 3, 1, 2, 3)

83. How do you find the difference between two sets?

o A) difference()

o B) subtract()

o C) remove()

o D) unique()

Answer: A) difference()
84. How do you get the keys from a dictionary?

o A) my_dict.keys()

o B) my_dict.get_keys()

o C) my_dict.all_keys()

o D) my_dict.list_keys()

Answer: A) my_dict.keys()

85. What will my_set.intersection(other_set) return?

o A) A set with elements that are in both my_set and other_set

o B) A set with elements that are in my_set but not in other_set

o C) A set with elements that are in either my_set or other_set

o D) A set with elements that are in my_set but not in other_set and vice versa

Answer: A) A set with elements that are in both my_set and other_set

86. What does the dict.items() method return?

o A) A view of the dictionary’s key-value pairs

o B) A list of dictionary keys

o C) A list of dictionary values

o D) A view of the dictionary’s values

Answer: A) A view of the dictionary’s key-value pairs

87. How do you create a set with elements from a string?

o A) set(string)

o B) list(string)

o C) create_set(string)

o D) string.to_set()

Answer: A) set(string)

88. What does dict.get(key, default) do if the key exists in the dictionary?

o A) Returns the value associated with the key

o B) Returns the default value

o C) Sets the key to the default value

o D) Returns the key

Answer: A) Returns the value associated with the key

89. How do you remove duplicates from a list?


o A) Convert the list to a set

o B) Use list.remove_duplicates()

o C) Use list.unique()

o D) Use list.discard()

Answer: A) Convert the list to a set

90. What is the output of [i for i in range(4) if i % 2 == 0]?

o A) [0, 2]

o B) [1, 3]

o C) [0, 1, 2, 3]

o D) [2, 4]

Answer: A) [0, 2]

91. How do you get the last element of a list?

o A) list[-1]

o B) list.last()

o C) list[len(list) - 1]

o D) list.end()

Answer: A) list[-1]

92. What will dict.update({'a': 1, 'b': 2}) do?

o A) Updates the dictionary with new key-value pairs

o B) Deletes the specified keys from the dictionary

o C) Returns the updated dictionary

o D) None of the above

Answer: A) Updates the dictionary with new key-value pairs

93. How do you check if a list is empty?

o A) if not list:

o B) if list == []:

o C) if len(list) == 0:

o D) All of the above

Answer: D) All of the above

94. What does the sorted() function do?

o A) Returns a sorted list of the specified iterable’s elements


o B) Sorts the list in place

o C) Returns the sorted list without altering the original

o D) Sorts the list and returns the sorted list in place

Answer: A) Returns a sorted list of the specified iterable’s elements

95. How do you check the type of an object?

o A) type(object)

o B) check_type(object)

o C) object.type()

o D) object.get_type()

Answer: A) type(object)

96. What will set([1, 2, 2, 3]) return?

o A) {1, 2, 3}

o B) [1, 2, 3]

o C) {1, 2, 2, 3}

o D) None

Answer: A) {1, 2, 3}

97. How do you convert a list to a tuple?

o A) tuple(list)

o B) list.to_tuple()

o C) convert_to_tuple(list)

o D) tuple.create(list)

Answer: A) tuple(list)

98. Which of the following will return True if a list is empty?

o A) not list

o B) list.is_empty()

o C) list.empty()

o D) list.length() == 0

Answer: A) not list

99. What is the output of "hello".upper()?

o A) HELLO

o B) hello
o C) Hello

o D) HELlo

Answer: A) HELLO

100. How do you get the number of items in a dictionary? - A) len(dict) - B) dict.count() -
C) dict.size() - D) dict.length()

python

Copy code

**Answer: A) `len(dict)`**

You might also like