Python - Code Based MCQs Ra - 31 Dec 23
Python - Code Based MCQs Ra - 31 Dec 23
Python
x = 10
y = "Hello"
z = x + y
(A) Integer
(B) String
(C) Float
(D) Error
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")
Python
for i in range(5):
if i == 3:
break
print(i)
greet("Alice")
greet("Bob")
Python
my_list = [1, 3, 5, 2, 4]
my_list.sort()
print(my_list)
Question 1
Concept tested: Variables and data types
Code:
Python
x = 10
y = "Hello"
print(x + y)
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")
Question 3
Find the error in the code:
Python
def my_function(x):
y = x * 2
print(y)
my_function("5")
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)
Question 5
Concept tested: Search algorithms (linear search)
Code:
Python
my_list = [7, 2, 9, 1]
target = 9
found = False
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"])
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)
Python
def outer_function(x):
def inner_function(y):
return x + y
return inner_function(5)
result = outer_function(10)
print(result)
Python
my_set1 = {1, 2, 3, 4}
my_set2 = {4, 5, 6}
intersection = my_set1 & my_set2
print(intersection)
Python
class MyClass:
def __init__(self, name):
self.name = name
obj1 = MyClass("Alice")
obj2 = obj1
obj2.name = "Bob"
print(obj1.name)
Python
import re
text = "The quick brown fox jumps over the lazy dog."
pattern = r"dog"
5. Concept: Recursion
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(result)
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.")
Python
import math
# 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.
Python
def my_function(numbers):
for i in range(len(numbers)):
if numbers[i] > 10:
numbers.remove(i) # Trying to remove element during
iteration
Python
data = [(x, x**2) for x in range(1, 6)]
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)
Python
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")
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.
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)
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")
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)
Python
score = int(input("Enter your score: "))
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
else:
print("Keep practicing!")
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(f"Eat your {fruit}!")
Python
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekend = ["Saturday", "Sunday"]
all_days = days + weekend
print(all_days[2])