Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Python - Code Based MCQs Ra - 31 Dec 23

This document contains questions about Python concepts like variables, data types, control flow, functions, lists, dictionaries, classes, file I/O, exceptions, modules and packages. The questions test understanding of Python syntax and semantics through code examples and identifying errors.

Uploaded by

Ramesh Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python - Code Based MCQs Ra - 31 Dec 23

This document contains questions about Python concepts like variables, data types, control flow, functions, lists, dictionaries, classes, file I/O, exceptions, modules and packages. The questions test understanding of Python syntax and semantics through code examples and identifying errors.

Uploaded by

Ramesh Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python, covering code output and error identification, along with explanations.

1. Variable Assignment and Data Types

Python
x = 10
y = "Hello"
z = x + y

What is the data type of z?

(A) Integer
(B) String
(C) Float
(D) Error

Answer: (D) Error


Explanation: You cannot directly add a number and a string using the + operator. It will result in
a type error. To concatenate them, you would need to convert the number to a string first.
2. Conditional Statements

Python
num = 15
if num > 10 and num % 2 == 0:
print("Number is even and greater than 10")
else:
print("Number is not even or not greater than 10")

What will be printed?


(A) Number is even and greater than 10 (B) Number is not even or not greater than 10 (C)
Syntax error (D) Nothing will be printed
Answer: (A) Number is even and greater than 10
Explanation: The condition num > 10 and num % 2 == 0 evaluates to True, as 15 is both
greater than 10 and even. Therefore, the first print statement executes.
3. Loops

Python
for i in range(5):
if i == 3:
break
print(i)

What will be printed?


(A) 0 1 2 3 (B) 0 1 2 (C) 3 (D) Nothing will be printed
Answer: (B) 0 1 2
Explanation: The loop iterates from 0 to 4, but the break statement exits the loop when i is 3.
Therefore, only the numbers 0, 1, and 2 are printed.
4. Functions
Python
def greet(name):
print("Hello, " + name + "!")

greet("Alice")
greet("Bob")

How many times will "Hello" be printed?


(A) Once (B) Twice (C) Three times (D) Zero times
Answer: (B) Twice
Explanation: The greet function is called twice, once with "Alice" and once with "Bob". Each call
prints "Hello," followed by the name.
5. Lists

Python
my_list = [1, 3, 5, 2, 4]
my_list.sort()
print(my_list)

What will be printed?


(A) [1, 2, 3, 4, 5] (B) [5, 4, 3, 2, 1] (C) [1, 3, 5, 2, 4] (D) An error message
Answer: (A) [1, 2, 3, 4, 5]
Explanation: The sort() method sorts the elements of the list in ascending order, resulting in [1,
2, 3, 4, 5] as the output.

Question 1
Concept tested: Variables and data types

Code:

Python
x = 10
y = "Hello"
print(x + y)

What will the output of this code be?


● (A) 10Hello
● (B) Hello10
● (C) 10
● (D) An error message

Answer: (D) An error message


Explanation: You cannot directly add a number (integer) and a string using the + operator. They
are different data types and require conversion before concatenation.

Question 2
Concept tested: Control flow (if statements)
Code:

Python
num = 25
if num > 10:
print("The number is greater than 10")
else:
print("The number is less than or equal to 10")

What will the output of this code be?


● (A) The number is greater than 10
● (B) The number is less than or equal to 10
● (C) Nothing will be printed
● (D) An error message

Answer: (A) The number is greater than 10


Explanation: The condition num > 10 is True, so the code within the if block executes, printing
the first message.

Question 3
Find the error in the code:

Python
def my_function(x):
y = x * 2
print(y)

my_function("5")

What is the error in this code?


● (A) The function is not defined correctly.
● (B) The function is called with a string argument, but it expects a numerical value.
● (C) The function does not have a return statement.
● (D) There is a syntax error in the function definition.

Answer: (B) The function is called with a string argument, but it expects a numerical value.
Explanation: The function tries to multiply the string "5" by 2, which is not possible. To fix this,
either call the function with a numerical argument (e.g., my_function(5)) or convert the string to a
number within the function.

Python concepts, including data structures and search & sorting algorithms:

Question 4
Concept tested: Data structures (lists)
Code:

Python
my_list = [1, 3, 5, 2, 4]
my_list.sort()
print(my_list)

What will the output of this code be?


● (A) [1, 2, 3, 4, 5]
● (B) [5, 4, 3, 2, 1]
● (C) [1, 3, 5, 2, 4]
● (D) An error message
Answer: (A) [1, 2, 3, 4, 5]
Explanation: The sort() method is used to sort the elements of a list in ascending order.

Question 5
Concept tested: Search algorithms (linear search)
Code:

Python
my_list = [7, 2, 9, 1]
target = 9
found = False

for item in my_list:


if item == target:
found = True
break

if found:
print("Target found in the list")
else:
print("Target not found in the list")
What will the output of this code be?
● (A) Target found in the list
● (B) Target not found in the list
● (C) An error message
● (D) The code will run indefinitely
Answer: (A) Target found in the list
Explanation: The code performs a linear search to find the target value in the list. If the target is
found, it prints a message indicating success.

Question 6
Find the error in the code:

Python
my_dictionary = {"name": "Alice", "age": 30}
print(my_dictionary["city"])

What is the error in this code?


● (A) The dictionary is not defined correctly.
● (B) The dictionary is empty.
● (C) The code tries to access a key that doesn't exist in the dictionary.
● (D) There is a syntax error in the dictionary definition.
Answer: (C) The code tries to access a key that doesn't exist in the dictionary.
Explanation: The dictionary doesn't have a key "city", so trying to access it will result in an
error.

Question 7
Concept tested: Sorting algorithms (bubble sort)
Code:

Python
def bubble_sort(my_list):
# Implement the bubble sort algorithm here
# ...

my_list = [6, 4, 2, 8, 1]
bubble_sort(my_list)
print(my_list)

What will the output of this code be (assuming the bubble sort algorithm is implemented
correctly)?
● (A) [1, 2, 4, 6, 8]
● (B) [6, 4, 2, 8, 1]
● (C) [8, 6, 4, 2, 1]
● (D) An error message
Answer: (A) [1, 2, 4, 6, 8]
Explanation: The bubble sort algorithm will arrange the list elements in ascending order.

Question 8
Concept tested: Data structures (tuples)
Code:

Python
my_tuple = (10, 20, 30)
my_tuple[1] = 50
print(my_tuple)

What will the output of this code be?


● (A) (10, 50, 30)
● (B) (10, 20, 30)
● (C) An error message
● (D) The code will run indefinitely

Answer: (C) An error message


Explanation: Tuples are immutable, meaning their elements cannot be changed after creation.
Trying to modify a tuple will result in an error.

1. Concept: Functions and scope

Python
def outer_function(x):
def inner_function(y):
return x + y
return inner_function(5)

result = outer_function(10)
print(result)

What will the output be?


● (A) 10
● (B) 15
● (C) Error: inner function not defined
● (D) Unexpected behavior due to closure
Answer: (B) 15
Explanation: The inner function captures the value of x from the outer function and adds it to
the argument y. Since x is 10 and y is 5, the result is 15.

2. Concept: Data structures (sets)

Python
my_set1 = {1, 2, 3, 4}
my_set2 = {4, 5, 6}
intersection = my_set1 & my_set2
print(intersection)

What will the output be?


● (A) {1, 2, 3}
● (B) {4}
● (C) Empty set
● (D) Error: cannot perform set operations
Answer: (B) {4}
Explanation: The & operator performs intersection on sets, finding elements present in both
sets. Only element 4 appears in both my_set1 and my_set2, hence the output.

3. Find the error:

Python
class MyClass:
def __init__(self, name):
self.name = name

obj1 = MyClass("Alice")
obj2 = obj1
obj2.name = "Bob"

print(obj1.name)

What is the error in this code?


● (A) Class definition is incorrect
● (B) Name attribute not defined in constructor
● (C) Object assignment creates shallow copy
● (D) Error accessing attribute after name change
Answer: (C) Object assignment creates shallow copy
Explanation: Modifying obj2.name changes only obj2's internal reference, not the object itself.
Since both obj1 and obj2 point to the same object in memory, obj1.name still reflects the original
value "Alice".

4. Concept: String manipulation and regular expressions

Python
import re

text = "The quick brown fox jumps over the lazy dog."
pattern = r"dog"

matches = re.findall(pattern, text)


print(matches)

What will be printed?


● (A) ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
● (B) ["dog"]
● (C) [0, 16, 32]
● (D) The entire text with pattern highlighted
Answer: (B) ["dog"]
Explanation: re.findall searches for all occurrences of the pattern in the text and returns a list of
matches. Since the pattern only matches "dog", that's the only element in the list.

5. Concept: Recursion

Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

result = factorial(5)
print(result)

What will the output be?


● (A) 0
● (B) 5
● (C) Infinity
● (D) Stack Overflow error
Answer: (D) Stack Overflow error
Explanation: This code implements a recursive function to calculate the factorial of a number.
However, without base case checks for large values of n, the recursion continues indefinitely,
causing a stack overflow error.

1. Concept: File I/O and exceptions

Python
try:
with open("myfile.txt", "r") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("File not found!")

if content:
print("File content:", content[:10])
else:
print("No content read from file.")

What will be printed if "myfile.txt" doesn't exist?


● (A) "File not found!"
● (B) "myfile.txt" and the first 10 characters of the file
● (C) "No content read from file."
● (D) An error message and traceback
Answer: (A) "File not found!"
Explanation: The try block attempts to open the file and read its content. If the file isn't found,
the FileNotFoundError exception is caught and "File not found!" is printed.

2. Concept: Modules and packages

Python
import math

area = math.pi * radius**2 # Assuming `radius` is defined elsewhere

# Option 1:
pi = math.pi
circumference = 2 * pi * radius

# Option 2:
from math import pi

circumference = 2 * pi * radius

Which option is preferred for using "pi" repeatedly for circumference calculations?
● (A) Option 1
● (B) Option 2
Answer: (B) Option 2
Explanation: Importing only the needed "pi" value from math is more efficient and avoids
importing unnecessary symbols, reducing memory usage and potential namespace conflicts.

3. Find the error:

Python
def my_function(numbers):
for i in range(len(numbers)):
if numbers[i] > 10:
numbers.remove(i) # Trying to remove element during
iteration

result = [15, 7, 3, 12, 9]


my_function(result)
print(result)

What is the error in this code?


● (A) Incorrect loop index for remove
● (B) Function modifies original list unexpectedly
● (C) Missing base case for loop
● (D) remove requires element index instead of position
Answer: (B) Function modifies original list unexpectedly
Explanation: Removing an element while iterating through the list with its index can cause
problems as the index of subsequent elements shifts. It's recommended to iterate over a copy of
the list or use reversed loop for deletion within the original list.

4. Concept: Lambda functions and list comprehension

Python
data = [(x, x**2) for x in range(1, 6)]

filtered_data = list(filter(lambda item: item[1] % 2 == 0, data))

result = [y for x, y in filtered_data]


print(result)

What will be printed?


● (A) [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
● (B) [4, 16]
● (C) [(1, 1), (4, 16)]
● (D) Syntax error
Answer: (B) [4, 16]
Explanation: The list comprehension in the first line generates a list of tuples with numbers and
their squares. The filter function then uses a lambda function to keep only tuples with even
squares. Finally, the second list comprehension extracts the squares from the filtered data,
resulting in the list [4, 16].

5. Concept: Decorators and function arguments

Python
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return wrapper

@my_decorator
def my_function(x, y):
return x + y

result = my_function(5, 3)
print(result)

What will be printed?


● (A) Before the function call
● (B) 8
● (C) After the function call
● (D) All of the above
Answer: (D) All of the above
Explanation: The decorator adds functionality before and after the decorated function
(my_function) is called. This results in printing "Before the

1. Concept: Date and time manipulation

Python
from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")

print(f"Current date: {formatted_date}")


print(f"Current time: {formatted_time}")

What will be the output if today's date is October 26, 2023 and the current time is
15:42:10?
● (A) Current date: 2023-10-27
● (B) Current time: 15:42:11
● (C) Both A and B
● (D) Neither A nor B
Answer: (D) Neither A nor B
Explanation: With today's date being October 26, 2023, the formatted date will be
"2023-10-26". Similarly, the formatted time will show the current time of 15:42:10. Neither of the
options in the answer choices matches both the date and time accurately.

2. Concept: Error handling and assertion

Python
def validate_age(age):
assert isinstance(age, int) and age >= 18, "Age must be an integer
>= 18"
return True

try:
validate_age("25")
except AssertionError as e:
print(e)

result = validate_age(22)
print(result)
What will be printed?
● (A) "Age must be an integer >= 18"
● (B) True
● (C) Both A and B
● (D) Syntax error
Answer: (C) Both A and B
Explanation: The validate_age function defines an assertion to check if the provided age is an
integer greater than or equal to 18. Passing "25" as a string will trigger the assertion error and
print "Age must be an integer >= 18". However, passing 22 as an integer within the try-except
block will correctly evaluate to True.
3. Find the error:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 25)
person2 = person1 # Copying reference instead of creating new object
person2.age = 30
print(person1.age)

What is the error in this code?


● (A) Class definition is incorrect
● (B) Missing attribute in constructor
● (C) Assignment to immutable attribute
● (D) Shallow copy leads to unexpected change in another object
Answer: (D) Shallow copy leads to unexpected change in another object
Explanation: When assigning person2 = person1, both variables point to the same object in
memory. Modifying person2.age to 30 also changes the value for person1.age, as they
reference the same data. This is due to shallow copying, where only object references are
copied, not the actual data they hold. To avoid this, use deepcopy functionality or create a new
instance with similar attributes.

4. Concept: Web scraping and libraries

Python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.content, "lxml")
# Option 1: Find all headlines with h1 tag
headlines = soup.find_all("h1")
# Option 2: Find specific element with class name
article = soup.find("article", class_="main-content")

Which option retrieves headlines from the webpage?


● (A) Option 1
● (B) Option 2
● (C) Both A and B
● (D) Neither A nor B
Answer: (A) Option 1
Explanation: Assuming the example webpage has headlines within h1 tags, using find_all("h1")
on the BeautifulSoup object will return a list of all those elements and their content, effectively
identifying the main headlines. Option 2 focuses on finding a specific element with a particular
class name ("main-content") and may not necessarily point to headlines depending on the
website structure.

1. Basic Operators and Input:

Python
number1 = int(input("Enter first number: "))
number2 = float(input("Enter second number: "))
product = number1 * number2
print(f"The product of {number1} and {number2:.2f} is {product:.2f}")

What type of error would occur if the user types "Hello" for the first number?
(A) Syntax error (B) Type error (C) Runtime error (D) No error, program will convert "Hello" to 0
Answer: (B) Type error
Explanation: Trying to convert "Hello" to an integer using int() will raise a TypeError because
"Hello" is not a valid numerical string.
2. String Manipulation:

Python
message = "Welcome to the Python world!"
first_word = message.split()[0]
last_word = message.split()[-1]
new_message = f"{last_word}, {first_word} is amazing!"
print(new_message)

What will be printed?


(A) Python world!, Welcome is amazing! (B) world!, Welcome is amazing! (C) Amazing, Python
world! (D) An error message
Answer: (A) Python world!, Welcome is amazing!
Explanation: We split the message into words, extract the first and last word, then create a new
sentence with the order reversed.

3. Control Flow with 'else' clause:

Python
score = int(input("Enter your score: "))
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
else:
print("Keep practicing!")

What will be printed if the user enters 65?


(A) Excellent! (B) Good job! (C) Keep practicing! (D) An error message
Answer: (C) Keep practicing!
Explanation: Since the score is neither >= 90 nor >= 70, the 'else' clause will be executed and
print "Keep practicing!".

4. Loops and Iteration:

Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(f"Eat your {fruit}!")

What will be printed?


(A) Eat your apple! (B) Eat your banana! (C) Eat your apple! Eat your cherry! (D) An error
message
Answer: (C) Eat your apple! Eat your cherry!
Explanation: The loop iterates over the fruits list. When it encounters "banana", the continue
statement skips to the next iteration, ignoring the print statement for that fruit. Therefore, only
"apple" and "cherry" are printed.

5. Simple Data Structures:

Python
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekend = ["Saturday", "Sunday"]
all_days = days + weekend
print(all_days[2])

What will be printed?


(A) Monday (B) Wednesday (C) Saturday (D) An error message
Explanation: The code combines two lists (days and weekend) using the + operator to create a
new list all_days. Accessing the third element (index 2) of this list should return "Wednesday".
Feel free to ask for more questions covering specific areas or adjusting the difficulty level!

You might also like