0% found this document useful (0 votes)
28 views

MCQ-2

The document contains a series of questions and options related to Python programming, covering topics such as random number generation, file handling, exception handling, and numpy operations. It includes fill-in-the-blank questions, true or false statements, code correction tasks, and theoretical questions. The content is structured to test knowledge and understanding of Python syntax and functionality.

Uploaded by

globalsadan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

MCQ-2

The document contains a series of questions and options related to Python programming, covering topics such as random number generation, file handling, exception handling, and numpy operations. It includes fill-in-the-blank questions, true or false statements, code correction tasks, and theoretical questions. The content is structured to test knowledge and understanding of Python syntax and functionality.

Uploaded by

globalsadan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Type: Fill in the blanks

Question 1: The _____ function is used to generate a random integer between 1 and 100
(inclusive) in Python.

Options:

a) rand()

b) randint(1, 100)

c) randomInt(1, 100)

d) random.randint(1, 100)

Question 2: The function used to calculate the square root of a number in Python is _______.

Options:

a) sqrt()

b) squareRoot()

c) root()

d) math.sqrt()

Question 3: The _____ function is used to get the current date in Python.

Options:

a) currentDate()

b) today()

c) getCurrentDate()

d) date.today()

Question 4: The _____ function is used to create an array filled with zeros in numpy.

Options:

a) zerosArray()

b) createZeros()

c) np.zeros()

d) zeros()

Type: True or False


Question 1: The random.choice() function in Python selects a random item from a list.

Options:

a) True

b) False

Question 2: The math.ceil() function in Python returns the smallest integer greater than or equal to
a given number.

Options:

a) True

b) False

Question 3: The datetime.timedelta() function in Python represents a duration of time.

Options:

a) True

b) False

Question 4: Numpy arrays can only have one dimension.

Options:

a) True

b) False

Type: Predict the Output

Question 1: What will be the output of the following code?

import random

print(random.randint(1, 10))

Options:

a) A random integer between 1 and 10

b) 1
c) 10
d) 11

Question 2: What will be the output of the following code?


import math
print(math.ceil(4.3)))
Options:
a) 4
b) 5
c) 4.0
d) 5.0

Question 3: What will be the output of the following code?

import random
print(random.choice(["apple", "banana", "cherry", "date"]))

Options:
a) A random fruit from the list
b) "apple"
c) "banana"
d) "cherry"

Question 4: What will be the output of the following code?

import math
print(math.pi)

Options:
a) 3.14
b) 3.141592653589793
c) 22/7
d) 3

Question 5: What will be the output of the following code?

import random
print(random.choice([True, False]))
Options:
a) True
b) False
c) Either True or False
d) None

Question:6 What will be the output of the following code?

import math
print(math.factorial(5))
Options:

a) 5
b) 15
c) 120
d) 25

Question 7: What will be the output of the following code?

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)

Options:
a) (3, 2)
b) (2, 3)
c) [3, 2]
d) [2, 3]

Question 8: What will be the output of the following code?

import numpy as np
arr = np.arange(10)
print(arr[2:5])

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

Type: Correct the Code

Question 1: Identify the error in the following code:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr[5] = 6
print(arr)

Options:
a) The list index is out of range.
b) There is no error.
c) The assignment operator is missing.
d) The list cannot contain integers.
Question 2: Identify the error in the following code:

import random

print(random.choice([1, 2, 3, 4]))

Options:

a) The code will raise an error.

b) There is no error.

c) The list contains only integers.

d) The choice function is not imported correctly.

Question 3: Identify the error in the following code:

import math
print(math.sqrt(-1))
Options:
a) The code will raise an error.
b) There is no error.
c) The sqrt function is not imported correctly.
d) Negative numbers cannot be square rooted.

Question 4: Identify the error in the following code:

from datetime import date


today = date.now()
print(today)
Options:
a) The code will raise an error.
b) There is no error.
c) The datetime module is not imported correctly.
d) The date object is not created correctly.
Question 5: Identify the error in the following code:
import random
numbers = [1, 2, 3, 4, 5]
shuffled = random.shuffle(numbers)
print(shuffled)
Options:
a) The code will raise an error.
b) There is no error.
c) The shuffle function is not imported correctly.
d) The shuffle function returns None and modifies the list in place.
Question 6: Identify the error in the following code:
import numpy as np
arr = np.arange(10)
print(np.middle(arr))
Option :
a) raise_error() # The code will raise an error.
b) np.median(arr) # The np.middle() function is not imported correctly.
c) np.mean(arr) # The median of a numpy array cannot be calculated.
d) np.middle(arr) # The function name should be np.median() instead of np.middle().

Type: Theory

Question 1: Which module in Python is used for handling dates and times?
Options:
a) time
b) date
c) datetime
d) calendar

Question 2: Which module in Python provides functions for generating random numbers?
Options:
a) randomize
b) randint
c) random
d) randomize

Question 3: What is the purpose of the math module in Python?


Options:
a) To perform mathematical operations like addition and subtraction.
b) To provide functions for working with complex numbers.
c) To perform mathematical operations like square root and logarithm.
d) To provide functions for working with fractions.

Question 5: What does the random.seed() function do in the random module?


Options:
a) It sets the seed for the random number generator, allowing reproducibility of results.
b) It generates a random seed for the random number generator.
c) It resets the random number generator to its initial state.
d) It initializes the random number generator with a specific seed.

Question 6: What is the significance of the math.floor() function in the math module?

Options:

a) It returns the largest integer less than or equal to a given number.

b) It rounds a given number to the nearest integer.

c) It returns the smallest integer greater than or equal to a given number.

d) It computes the factorial of a given number.

Question1 _____ function is used to open a file in Python.

Options:

open()

openfile()

display()

show()

Question 2 In _____ mode all files are opened by default

Options:

Read mode
Append mode

Write mode

Question 3 The readlines() method returns………

Options:

List of integers

List of lines

single line

Question 4 When you open a file in a+ mode file pointer will be at………

Options:

a)Beginning of file

b)End of file

Question:1 We can create a text file in Python?

Options:

a) True

b) False

Question: 2 delete() function is used to delete a file in Python?

a) False

b) True

Question: 3 In binary files each line is terminated with a special character.


a) False

b) True

Question: 4 There are three ways to read data from a text file.

a) False

b) True

Question 1: Correct syntax of file.writelines() is?

Options:

a) file.writelines(sequence)

b) fileObject.writelines()

c) fileObject.writelines(sequence)

Question 2: What is the correct syntax to remove() a file?

Options:

a) remove(file_name)

b) remove(() , file_name))

c) none of the mentioned

Question 3 : What is the correct syntax of rename() a file?

Options:

a)rename(current_file_name, new_file_name)

b)rename(new_file_name, current_file_name,)

c) rename(()(current_file_name, new_file_name))
d)none of the mentioned

Question 4.: Choose the right code to open the file “hello.txt” in read-only mode.

Options:

open('hello.txt', 'r')

open('hello.txt', 'ro')

open('hello.txt', 'read_only')

open('w', 'hello.txt')

Question 5 : Choose the right code to open the file “animals.txt” in write-only mode.

Options:

a) open('animals.txt', 'r')

b) open('animals.txt', 'write_only')

c)open('animals.txt', 'w+')

d)open('animals.txt', 'w')

Question 6: Choose the right code to open the file “fruit.txt” in append mode.

Options:

a) open('fruit.txt', 'r+')

b) open('fruit.txt', 'w+')

c) open('fruit.txt', 'a')

d) open('fruit.txt', 'a+')

Question 7:Correct code to open a file c:\text.txt for reading is


a)f = open(file = “c:\test.txt”, “r”)

b)f = open(“c:\\test.txt”, “r”)

c)f = open(file = “c:\\test.txt”, “r”)

d)f = open(“c:\test.txt”, “r”)

Question 1: What will be the output of the following Python code?

You have a file named "data.txt" containing the following content:

10 20 30 40 50

You want to read the contents of this file, calculate the sum of all numbers, and then write this
sum to another file named "output.txt". Which of the following Python code snippets correctly
accomplishes this task?

A.with open("data.txt", "r") as file:

numbers = file.read().split()

total = sum(numbers)

with open("output.txt", "w") as output_file:

output_file.write(total)

B.with open("data.txt", "r") as file:

numbers = file.read().split()

total = sum(map(int, numbers))

with open("output.txt", "w") as output_file:

output_file.write(str(total))

C.with open("data.txt", "r") as file:

numbers = file.readlines()
total = sum(map(int, numbers))

with open("output.txt", "w") as output_file:

output_file.write(total)

d.with open("data.txt", "r") as file:

numbers = file.readlines()

total = sum([int(num) for num in numbers])

with open("output.txt", "w") as output_file:

output_file.write(str(total))

Question 2 What will be the output of the following Python code?

f = None

for i in range (5):

with open("data.txt", "w") as f:

if i > 2:

break

print(f.closed)

a) True

b) False

c) None

d) Error
Question 3 What will be the output of the following Python code?

str = raw_input("Enter your input: ");

print "Received input is : ", str

a)

Enter your input: Hello Python

Received input is : Hello Python

b)

Enter your input: Hello Python

Received input is : Hello

c)

Enter your input: Hello Python

Received input is : Python

d) None of the mentioned

Question 4 What will be the output of the following Python code?

fo = open("foo.txt", "wb")

print "Name of the file: ", fo.name

fo.flush()

fo.close()

a) Compilation Error

b) Runtime Error

c) No Output

d) Flushes the file when closing them


Question 1:What function is used to change the size of a file?

a)truncate()

b)size()

c)setsize()

d) both a and b

Question 2:What is the difference between r+ and w+ modes?

a)No difference

b)In case of r+ the pointer is initially placed at the beginning of the file and the pointer is at the end
for w+

c) In case of w+ the pointer is initially placed at the beginning of the file and the pointer is at the
end for r+

d) Depends on the operating system

Question 3 What function is used to simultaneously write multiple lines in a file?

write()

writelines()

writeall()

None of above

Question 4 From the following which file mode is used to read from a binary file?

R+

Rb
Question 5:What function is used to open a file in Python for reading?

a) open_file()

b) read_file()

c) open()

d) read()

Question 6 What function is used to read the entire contents of a file as a string in Python?

a) read_file()

b) read_string()

c) readlines()

d) read()

How do you get the current position within the file?

a) fp.seek()

b) fp.tell()

c) fp.loc

d) fp.pos

Question:

1. The ______ block is used to wrap around the code that may raise an exception.

a) try

b) catch

c) except

d) raise
In Python, the _____ keyword is used to define code that executes after the 'try' and 'except' blocks,
regardless of whether an exception occurs or not.

a) final

b) else

c) catch

d) finally

3. The finally block is executed ____________ whether an exception occurs or not.

a) only if an excption occurs

b) only if no exception occurs

c) regardless of whether an exception occurs or not

d) only when the try block is empty

4. The _____ keyword is used to handle exceptions when no specific exception type is specified.

a) any

b) catch

c) except

d) all

1. An exception is an error that occurs during the execution of a program.

a) True

b) False
2. The else block in Python's exception handling is executed if no exceptions are raised in the try
block.

a) True

b) False

3. A custom exception in Python must inherit from the 'Exception' class.

a) True

b) False

4. The 'except' block in Python is mandatory for exception handling.

a) True

b) False

1. Identify the error in the following code snippet:

try:

result = 10 / 0

except Exception as e:

print("An error occurred:", e)

a) Missing colon after try

b) Missing colon after except

c) An error occurred: division by zero

d) No error
2. What is the correct syntax for handling an exception in Python?

a)

try:

# Code that may raise an exception

catch Exception as e:

# Handle the exception

b)

try:

# Code that may raise an exception

except Exception as e:

# Handle the exception

c)

try:

# Code that may raise an exception

finally:

# Handle the exception

d)

try:

# Code that may raise an exception

else:

# Handle the exception

3. Identify the mistake in the following code snippet:

try:
print("Hello")

except:

print("An error occurred")

else:

print("No errors occurred")

a) 'except' block should be followed by 'finally' block

b) 'else' block should be nested inside the 'except' block

c) There is no mistake

d) 'else' block should be followed by 'finally' block

5. Identify the correct way to raise a custom exception named 'MyCustomError' in Python.

class MyCustomError(Exception):

pass

try:

throw MyCustomError

except MyCustomError:

print("Custom Error")

a) raise CustomError()

b) throw MyCustomError()

6. What should replace ______ in the code below to handle ValueError?


try:

x = int(input("Enter a number: "))

except ______:

print("Invalid input.")

a) IntException

b) ValueError

c) SyntaxError

d) IOError

7. Correct the following code snippet to handle both ZeroDivisionError and ValueError:

try:

x = int(input("Enter a number: "))

result = 10 / x

except ZeroDivisionError:

print("Error: Division by zero")

except ValueError:

print("Error: Invalid input")

a) Add 'except ValueError' before 'except ZeroDivisionError'

b) Add 'except ValueError' after 'except ZeroDivisionError'

c) Replace 'except ZeroDivisionError' with 'except ValueError'

d) None of the above


1. What will be the output of the following code?

try:

print(10 / 0)

except ZeroDivisionError:

print("Cannot divide by zero.")

a) Cannot divide by zero

b) 0

c) Error: Division by zero

d) None

2. What will be the output of the following code?

try:

raise ValueError("Error")

except ValueError as e:

print(e)

finally:

print("Finally block executed.")

a) Error

Finally block executed.

b) Finally block executed.


Error

c) Error

Error

Finally block executed.

d) None of the above

3. What will be the output of the following code?

x = "5"

y = "hello"

try:

z=x+y

print(z)

except TypeError:

print("Error: cannot add an int and a str")

a) hello

b) 5

c) 5hello

d) Error: cannot add an int and a str

5. What will be the output of the following code?

try:

print("Hello" + 10)

except TypeError:
print("Error: Type mismatch")

a) Error: Type mismatch

b) Hello

c) Hello10

d) None of the above

6. What will be the output of the following code?

a = [1, 2, 3]

try:

print ("Second element = %d" %(a[1]))

print ("Fourth element = %d" %(a[3]))

except:

print ("An error occurred")

a) An error occurred

Second element = 2

b) Second element = 2

c) An error occurred

d) Second element = 2

An error occurred

1. What is the primary purpose of exception handling in programming languages?


a) To terminate the program

b) To ignore errors

c) To handle errors gracefully and prevent program crashes

d) To print error messages

2. What is the advantage of using the finally block in exception handling?

a) It catches exceptions

b) It handles exceptions gracefully

c) It executes code regardless of whether an exception occurs or not

d) It terminates the program

3. What is an exception in Python?

a) A syntax error

b) An error that occurs during program execution

c) A logical error

d) A warning message

4. What is the purpose of the 'finally' block in Python exception handling?

a) To catch and handle exceptions

b) To execute code regardless of whether an exception occurs or not

c) To specify alternative code paths


d) None of the above

5. Which of the following statements is true regarding custom exceptions in Python?

a) Custom exceptions must always inherit from the built-in Exception class.

b) Custom exceptions are automatically handled by the Python interpreter.

c) Custom exceptions can only be raised using the raise keyword.

d) Custom exceptions provide a way to create and raise user-defined errors in Python programs.

6. In Python, what is the primary purpose of using custom exceptions?

a) To replace built-in exceptions with custom error messages.

b) To handle standard errors more efficiently.

c) To create specialized error types for specific situations in a program.

d) To suppress error messages generated by the Python interpreter.

You might also like