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

Programming With Python (CT108-3-1-PYP) ALL 12 CHAPTERS MCQ

Programming with Python (CT108-3-1-PYP) ALL 12 CHAPTERS MCQ FOR PRACTISE

Uploaded by

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

Programming With Python (CT108-3-1-PYP) ALL 12 CHAPTERS MCQ

Programming with Python (CT108-3-1-PYP) ALL 12 CHAPTERS MCQ FOR PRACTISE

Uploaded by

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

CHAPTER 1

Which of the following steps is NOT part of developing a program?

● A. Define the problem


● B. Code the algorithm
● C. Purchase software licenses
● D. Document and maintain the program

What is the first step in developing a program?

● A. Outline the solution


● B. Define the problem
● C. Test the algorithm
● D. Code the program

In the context of problem-solving, which component is NOT part of the IPO chart?

● A. Input
● B. Output
● C. Processing
● D. Feedback

Which of the following is a common issue in problem-solving?

● A. Defining the problem too clearly


● B. Analyzing the problem without assumptions
● C. Incomplete list of alternatives
● D. Sequencing solutions logically

The step "Test the algorithm for correctness" is essential because:

● A. It ensures the program is error-free


● B. It verifies that the instructions perform the intended tasks
● C. It involves running the program on a computer
● D. It documents the program

What is the purpose of pseudocode?

● A. To execute a program directly


● B. To represent an algorithm in a high-level language
● C. To design the user interface
● D. To simplify the logic of the problem
Which keyword is commonly used for input operations in pseudocode?

● A. PRINT
● B. COMPUTE
● C. GET
● D. SET

In a flowchart, which symbol represents a decision point?

● A. Rectangle
● B. Diamond
● C. Oval
● D. Arrow

Which operation is NOT typically represented by pseudocode keywords?

● A. Input
● B. Arithmetic operations
● C. User interface design
● D. Repetition

What is the key difference between pseudocode and flowcharts?

● A. Pseudocode uses graphical symbols


● B. Flowcharts are written in high-level language
● C. Pseudocode is written in structured English
● D. Flowcharts include only textual descriptions

Which pseudocode keyword is used to start a loop that continues while a condition is true?

● A. IF
● B. WHILE
● C. PRINT
● D. SET

Which of the following is an example of assigning a value to a variable in pseudocode?

● A. PRINT total_price
● B. SET total_price to 0
● C. DISPLAY total_price
● D. INPUT total_price

In problem-solving, what does "desk checking" an algorithm involve?


● A. Writing the algorithm in a programming language
● B. Running the algorithm on a computer
● C. Manually tracing through the algorithm with test data
● D. Documenting the algorithm

Which symbol in a flowchart indicates the starting or stopping point?

● A. Process symbol
● B. Terminal symbol
● C. Decision symbol
● D. Connector symbol

Which of the following is TRUE about algorithms?

● A. They must be written in a specific programming language


● B. They should be ambiguous to cover multiple scenarios
● C. They must eventually end
● D. They are only used for mathematical calculations

Which keyword in pseudocode indicates the beginning of an alternative action based on a


condition?

● A. THEN
● B. IF
● C. ELSE
● D. ENDIF

In a flowchart, which symbol is used to represent input or output operations?

● A. Rectangle
● B. Parallelogram
● C. Oval
● D. Arrow

Which of the following best describes the term "processing" in the context of an algorithm?

● A. Receiving input from the user


● B. Performing calculations or operations
● C. Displaying the output to the user
● D. Storing the data in memory

What is the main purpose of documenting a program?


● A. To write the code in a high-level language
● B. To facilitate maintenance and updates
● C. To test the program for correctness
● D. To develop the pseudocode

Which pseudocode keyword is used to signify the end of a conditional statement?

● A. ENDIF
● B. ELSE
● C. END
● D. STOP

What does the term "algorithm" refer to in computer programming?

● A. A detailed step-by-step procedure for solving a problem


● B. A high-level programming language
● C. A set of graphical symbols used in flowcharts
● D. A type of software used for coding
● Parallelogram

In the context of programming, what is meant by "maintaining the program"?

● A. Writing the initial code


● B. Running the program on a computer
● C. Making necessary updates and improvements over time
● D. Developing the pseudocode

Which flowchart symbol is used to represent a process or operation?

● A. Rectangle
● B. Diamond
● C. Oval
● D. Parallelogram

Which of the following actions does NOT typically occur during the "code the algorithm" step?

● A. Writing the code in a specific programming language


● B. Designing the solution algorithm
● C. Compiling the code
● D. Identifying syntax errors

In a pseudocode algorithm, which keyword would you use to indicate an output operation?
● A. GET
● B. PRINT
● C. SET
● D. INPUT

What is the primary advantage of using pseudocode in program design?

● A. It can be executed directly by the computer


● B. It provides a visual representation of the algorithm
● C. It allows the programmer to focus on logic without syntax
● D. It is a formal documentation standard

Which of the following describes the role of a "defining diagram" or IPO chart in
problem-solving?

● A. It provides a step-by-step procedure for the algorithm


● B. It visually represents the flow of execution
● C. It outlines the inputs, processing, and outputs of the problem
● D. It documents the solution in a specific programming language

====================================================================

CHAPTER 2

1. Which of the following is NOT a relational operator in Python?


○ A. >
○ B. >=
○ C. &&
○ D. !=
2. The AND logical operator in Python is represented by:
○ A. ||
○ B. &&
○ C. and
○ D. &
3. In a flowchart, the symbol used to represent a decision point is:
○ A. Rectangle
○ B. Oval
○ C. Diamond
○ D. Parallelogram
4. Which of the following statements is true about the OR logical operator?
○ A. It is true only if both conditions are true
○ B. It is true if at least one condition is true
○ C. It reverses the value of an expression
○ D. It checks for equality
5. The condition in a while loop is checked:
○ A. After each iteration
○ B. Before each iteration
○ C. Only at the beginning
○ D. Only at the end
6. Which of the following is a pre-test loop structure in Python?
○ A. do-while
○ B. repeat-until
○ C. for
○ D. while

In the following pseudocode, what will be the value of service_charge if account_balance is 400?

IF account_balance < 300 THEN


service_charge = 5.00
ELSE
service_charge = 2.00
ENDIF

7.
○ A. 5.00
○ B. 2.00
○ C. 0.00
○ D. 7.00
8. Which of the following is a correct representation of a relational expression?
○ A. (x > y) and (y > z)
○ B. (x => y) or (z <= y)
○ C. (x <== z) and (y == z)
○ D. (x =< z) or (y != z)
9. In a for loop, the initialization of the loop variable occurs:
○ A. At the end of the loop
○ B. Before the loop starts
○ C. In the loop body
○ D. After each iteration
10. Which pseudocode keyword indicates the end of a conditional block?
○ A. THEN
○ B. ELSE
○ C. ENDIF
○ D. IF
11. A _________ structure allows you to choose between two or more alternatives.
○ Answer: Selection
12. In a flowchart, the _________ symbol is used to represent the start and end of a process.
○ Answer: Oval
13. The logical operator used to negate a condition is _________.
○ Answer: NOT
14. In a nested selection structure, an _________ statement appears within another IF
statement.
○ Answer: IF
15. The keyword _________ is used in pseudocode to represent an output operation.
○ Answer: PRINT
16. True or False: In Python, the logical operator for OR is represented by ||.
○ Answer: False
17. True or False: A while loop checks its condition before executing the loop body.
○ Answer: True
18. True or False: In a flowchart, a rectangle is used to represent a decision point.
○ Answer: False
19. True or False: The ELSE statement in pseudocode is used to specify actions to be taken
when the IF condition is true.
○ Answer: False
20. True or False: The AND logical operator in Python requires both conditions to be true for
the combined expression to be true.
○ Answer: True
21. Which keyword in pseudocode indicates the beginning of a conditional block?
○ A. IF
○ B. THEN
○ C. ELSE
○ D. ENDIF
22. The relational operator != in Python means:
○ A. Less than
○ B. Equal to
○ C. Greater than
○ D. Not equal to
23. Which of the following is an example of a post-test loop structure?
○ A. while
○ B. for
○ C. do-whiletea
○ D. repeat-until
24. In pseudocode, which keyword is used to signify an output operation to the screen?
○ A. GET
○ B. INPUT
○ C. DISPLAY
○ D. READ
25. The control structure that repeats a block of code as long as a condition is true is called:
○ A. Selection
○ B. Sequence
○ C. Iteration
○ D. Condition

26. The _________ logical operator is used to combine multiple conditions where all
conditions must be true.
○ Answer: AND
27. In a flowchart, the _________ symbol is used to indicate a process or operation.
○ Answer: Rectangle
28. A _________ loop tests the condition after executing the loop body.
○ Answer: Post-test
29. The _________ operator is used to compare two values for equality in Python.
○ Answer: ==
30. A _________ structure in programming is used to execute a set of statements
sequentially.
○ Answer: Sequence

Which control structure is used for making decisions in algorithms?

● A. Iteration
● B. Sequence
● C. Selection
● D. Repetition

The process of repeating a set of statements is known as:

● A. Selection
● B. Iteration
● C. Sequence
● D. Condition

Which of the following statements about the IF statement is true?

● A. It can only be used once in an algorithm


● B. It cannot be nested within another IF statement
● C. It allows a choice between two paths based on a condition
● D. It must always be followed by an ELSE statement

In pseudocode, the keyword used to represent a loop that continues while a condition is true is:

● A. FOR
● B. WHILE
● C. REPEAT
● D. UNTIL

Which logical operator would you use to combine conditions where at least one must be true?

● A. AND
● B. OR
● C. NOT
● D. XOR

What is the output of the following pseudocode if x is 5 and y is 10?

IF x > y THEN
DISPLAY "X is greater"
ELSE
DISPLAY "Y is greater"
ENDIF

● A. X is greater
● B. Y is greater
● C. X and Y are equal
● D. No output

The condition in a for loop is checked:

● A. Only once at the beginning


● B. Only once at the end
● C. Before each iteration
● D. After each iteration

Which of the following is NOT a feature of a good algorithm?

● A. Ambiguous steps
● B. Simplicity
● C. Precision
● D. Correctness
The keyword used in pseudocode to signify a comparison is:

● A. COMPARE
● B. IF
● C. CHECK
● D. TEST

In a nested IF statement, which statement is true?

● A. The inner IF must not have an ELSE


● B. The outer IF cannot have an ELSE
● C. The inner IF can only test the same variable as the outer IF
● D. The inner IF can be an entirely separate condition

Which pseudocode keyword represents an action that should only occur if a specified condition
is false?

● A. THEN
● B. ELSE
● C. ENDIF
● D. IF

In a pre-test loop structure, the loop body is:

● A. Executed before the condition is checked


● B. Executed only once
● C. Executed as long as the condition is true
● D. Never executed

Which of the following control structures allows multiple selections based on different
conditions?

● A. Simple IF
● B. Nested IF
● C. Switch-case
● D. For loop

Which keyword is used in pseudocode to represent the end of a loop structure?

● A. ENDLOOP
● B. ENDIF
● C. ENDWHILE
● D. STOP
What is the primary purpose of using flowcharts in programming?

● A. To execute the program


● B. To visually represent the algorithm
● C. To write the actual code
● D. To debug the program

Which statement is true about a sentinel value in a loop?

● A. It is a valid input value


● B. It indicates the end of the loop
● C. It must be the smallest possible value
● D. It cannot be a negative number

Which of the following best describes the structure of a WHILE loop?

● A. The loop continues as long as the condition is true


● B. The loop continues until the condition becomes true
● C. The loop runs a fixed number of times
● D. The loop runs only once if the condition is true

In an algorithm, which step is performed after defining the problem?

● A. Code the algorithm


● B. Outline the solution
● C. Test the algorithm
● D. Document the program

The keyword ________ is used to indicate a process or operation in a flowchart.

● A. PROCESS
● B. OPERATION
● C. ACTION
● D. COMPUTE

===================================================================

CHAPTER 3

Which of the following is NOT a feature of Python?

● A. Strongly typed
● B. Object-oriented
● C. Static typing
● D. Free and open-source

Python was first implemented in:

● A. 1985
● B. 1989
● C. 1991
● D. 2000

Which statement is true about Python's indentation?

● A. Indentation is optional in Python


● B. Indentation indicates block structure
● C. Indentation is used only for comments
● D. Indentation can be mixed with tabs and spaces freely

In Python, the keyword used to print output to the console is:

● A. echo
● B. printf
● C. print
● D. output

Which of the following is NOT a basic datatype in Python?

● A. Integer
● B. Float
● C. Character
● D. String

Python variables do not require _________ before use.

● A. Initialization
● B. Declaration
● C. Assignment
● D. Naming

Which of the following versions of Python is recommended for new projects?

● A. Python 2.7
● B. Python 3.x
● C. Python 1.6
● D. Python 2.6

What will be the output of the following Python code?

x = 10
y=5
print(x + y)

● A. 10
● B. 5
● C. 15
● D. Error

Which of the following statements is true about Python lists?

● A. Lists are immutable


● B. Lists can contain elements of different types
● C. Lists must contain elements of the same type
● D. Lists do not support indexing

The Python expression 5 // 2 evaluates to:

● A. 2.5
● B. 2
● C. 3
● D. 1

In Python, a string can be enclosed in:

● A. Single quotes
● B. Double quotes
● C. Triple quotes
● D. All of the above

Which operator is used for string concatenation in Python?

● A. +
● B. &
● C. *
● D. %
What is the result of the following code snippet?

a = "Python"
b = "Programming"
print(a + " " + b)

● A. PythonProgramming
● B. Python Programming
● C. "Python" "Programming"
● D. Error

In Python, which of the following is a valid variable name?

● A. 2nd_value
● B. value_2
● C. value-2
● D. value.2

Which of the following is used to create a comment in Python?

● A. //
● B. /*
● C. #
● D. --

Which of the following is the correct way to write a function in Python?

● A. def myFunction {}
● B. function myFunction()
● C. def myFunction():
● D. function: myFunction()

What is the purpose of the import statement in Python?

● A. To include external libraries or modules


● B. To define a function
● C. To declare a variable
● D. To print output to the console

Which keyword is used to handle exceptions in Python?

● A. try
● B. except
● C. finally
● D. All of the above

Which of the following will raise a TypeError in Python?

● A. 5 + 5
● B. "5" + "5"
● C. 5 + "5"
● D. "5" * 2

What is the output of the following code?

for i in range(3):
print(i)

● A. 1 2 3
● B. 0 1 2
● C. 1 2 3 4
● D. 0 1 2 3

Which of the following data types is mutable in Python?

● A. String
● B. List
● C. Tuple
● D. Integer

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

● A. append()
● B. add()
● C. insert()
● D. extend()

Which statement will execute a block of code only if a specified condition is true?

● A. for
● B. while
● C. if
● D. def
In Python, which keyword is used to start a loop that will continue as long as a specified
condition is true?

● A. for
● B. while
● C. loop
● D. until

Which of the following is the correct way to open a file named data.txt for reading in Python?

● A. open("data.txt", "r")
● B. open("data.txt", "w")
● C. open("data.txt", "rb")
● D. open("data.txt")

What is the output of the following Python code?

x = [1, 2, 3, 4, 5]
print(x[1:3])

● A. [1, 2]
● B. [2, 3]
● C. [1, 2, 3]
● D. [2, 3, 4]

Which of the following functions is used to find the length of a list in Python?

● A. length()
● B. len()
● C. count()
● D. size()

What will be the result of the following code?

x = 10
y=5
x, y = y, x
print(x, y)

● A. 10 5
● B. 5 10
● C. 0 0
● D. Error

Which of the following is a valid dictionary declaration in Python?

● A. {1, 2, 3}
● B. [1, 2, 3]
● C. {1: "one", 2: "two", 3: "three"}
● D. (1, 2, 3)

Which method is used to remove an item from a list by its value in Python?

● A. delete()
● B. remove()
● C. pop()
● D. discard()

Which of the following is used to create a new set in Python?

● A. []
● B. {}
● C. ()
● D. set()

What will be the output of the following code?

a = [1, 2, 3]
b=a
b.append(4)
print(a)

● A. [1, 2, 3]
● B. [1, 2, 3, 4]
● C. [4, 2, 3, 4]
● D. Error

Which function is used to convert a string to an integer in Python?

● A. str()
● B. int()
● C. float()
● D. chr()
What is the purpose of the pass statement in Python?

● A. To pass control to the next function


● B. To raise an exception
● C. To do nothing and move to the next line of code
● D. To break out of a loop

Which of the following is NOT a valid Python keyword?

● A. global
● B. nonlocal
● C. public
● D. lambda

What will be the result of the following code?

def func():
x = 10
print(x)

x = 20
func()
print(x)

● A. 10 20
● B. 20 10
● C. 10 10
● D. 20 20

Which of the following is NOT a valid string method in Python?

● A. upper()
● B. lower()
● C. split()
● D. replace()

Which of the following methods is used to remove whitespace from the beginning and end of a
string in Python?

● A. strip()
● B. trim()
● C. remove()
● D. clear()

Which of the following is used to create an anonymous function in Python?

● A. def
● B. lambda
● C. func
● D. anon

What will be the result of the following code?

x = "Hello"
y = "World"
print(x * 2 + y)

● A. Hello World
● B. HelloHello World
● C. HelloHelloWorld
● D. Error

===============================================================

CHAPTER 4

Which of the following is a correct variable name in Python?

● A. 2nd_variable
● B. variable_2
● C. variable-2
● D. variable.2

In Python, which operator is used to assign a value to a variable?

● A. ==
● B. :=
● C. =
● D. =>

What will be the result of the following code?

a, b, c = 3, 4.5, "Python"
print(a, b, c)
● A. 3 4 Python
● B. 3 4.5 Python
● C. 3.0 4.5 Python
● D. Error

Which of the following is true about variable names in Python?

● A. They can start with a number


● B. They can contain spaces
● C. They can contain special characters like @, #, %
● D. They are case-sensitive

What is the output of the following code snippet?

number = 10
number = 2.5
print(number)

● A. 10
● B. 2.5
● C. Error
● D. None

Which of the following statements about Python variables is FALSE?

● A. Variables must be declared before they are used


● B. Python is an interpreted language
● C. Variable types are inferred
● D. Variables are references to objects

Which of the following is used to declare a global variable inside a function?

● A. global
● B. Global
● C. GLOBAL
● D. public

What will be the output of the following code?

def add():
a = 20
b = 10
c=a+b
print("The sum is", c)
add()

● A. The sum is 20
● B. The sum is 10
● C. The sum is 30
● D. Error

Which of the following statements correctly declares and assigns a value to a constant in Python?

● A. PI = 3.14
● B. const PI = 3.14
● C. constant PI = 3.14
● D. define PI = 3.14

Which of the following functions is used to check the data type of a variable in Python?

● A. checktype()
● B. datatype()
● C. typeof()
● D. type()

What will be the result of the following expression?

5 // 2

● A. 2.5
● B. 2
● C. 3
● D. 2.0

Which of the following operators has the highest precedence in Python?

● A. +
● B. **
● C. *
● D. /
What will be the result of the following expression?

2 ** 3 ** 2

● A. 64
● B. 512
● C. 8
● D. 256

What will be the output of the following code?

x = 10
y=5
result = x + y * x / y - x
print(result)

10 + 50/5 - 10
10 + 10 - 10
20 - 10
10

● A. 10.0
● B. 5.0
● C. 15.0
● D. 20.0

Which of the following statements is true about the type() function in Python?

● A. It returns the memory address of the variable


● B. It returns the size of the variable
● C. It returns the data type of the variable
● D. It returns the value of the variable

Which of the following statements about Boolean operators in Python is FALSE?

● A. and returns True if both operands are true


● B. or returns True if at least one operand is true
● C. not returns the opposite Boolean value
● D. && is a valid Boolean operator in Python
What will be the output of the following code?

x = True
y = False
result = x and not y
print(result)

● A. True
● B. False
● C. None
● D. Error

Which of the following is a valid expression in Python?

● A. 5 + 2 * 3
● B. 5 + * 2
● C. 5 / + 2
● D. 5 + 2 *

What is the purpose of the global keyword in Python?

● A. To declare a variable as a constant


● B. To define a variable inside a function
● C. To access a global variable inside a function
● D. To create a local variable inside a function

What will be the output of the following code?

a = 10
b=a*5
c = "Your result is: "
print(c + str(b))

● A. Your result is: 50


● B. Your result is: 1050
● C. Error
● D. None

Which of the following statements is true about local variables in Python?

● A. They can be accessed outside the function


● B. They are defined using the global keyword
● C. They can only be used within the function where they are defined
● D. They have a global scope

Which of the following will convert a string to an integer in Python?

● A. int("123")
● B. str(123)
● C. float("123.45")
● D. string("123")

What is the output of the following code snippet?

a = 10
b=5
result = a > b and a < 20
print(result)

● A. True
● B. False
● C. None
● D. Error

Which of the following is NOT a Python keyword?

● A. None
● B. False
● C. True
● D. value

Which of the following statements is true about type conversion in Python?

● A. It can only be done using the type() function


● B. It is automatic for arithmetic operations
● C. It requires explicit functions like int(), float(), str()
● D. It is not supported in Python

What will be the output of the following code?

a = "5"
b = int(a)
c=b+5
print(c)

● A. 55
● B. 10
● C. Error
● D. None

Which of the following is used to comment a single line in Python?

● A. //
● B. /*
● C. #
● D. ---

Which of the following is NOT a valid way to declare multiple variables in a single line in
Python?

● A. a, b, c = 1, 2, 3
● B. a = b = c = 1
● C. a = 1; b = 2; c = 3
● D. a b c = 1 2 3

What will be the result of the following expression?

7%3

● A. 2
● B. 1
● C. 3
● D. 0

Which of the following is the correct way to use the global keyword inside a function?

● A. global x = 10
● B. def global x
● C. global x; x = 10
● D. x = global 10

What is the result of the following code?

def test():
x = 10
y=5
print(x + y)

test()
print(x)

● A. 15 and 10
● B. 15 and Error
● C. 10 and 15
● D. Error and 10

Which of the following statements is used to exit a loop prematurely in Python?

● A. exit
● B. stop
● C. break
● D. return

Which of the following will raise a ValueError in Python?

● A. int("123")
● B. float("123.45")
● C. int("abc")
● D. str(123)

What is the result of the following code?

x=3
y = x ** 2
print(y)

● A. 6
● B. 9
● C. 3
● D. 8

Which of the following operators is used for exponentiation in Python?

● A. ^
● B. **
● C. %
● D. $

Which of the following is true about the and operator in Python?

● A. It returns True if both operands are true


● B. It returns True if at least one operand is true
● C. It reverses the value of the operand
● D. It is not a valid operator in Python

What will be the output of the following code?

x = 10
y=5
print(x * y)

● A. 15
● B. 50
● C. 5
● D. 2

Which function is used to find the length of a string in Python?

● A. length()
● B. len()
● C. size()
● D. count()

=================================================================

CHAPTER 5

What is the output of the following code snippet?

x = 10
if x < 10:
print("Less than 10")
elif x == 10:
print("Equal to 10")
else:
print("Greater than 10")
● A. Less than 10
● B. Equal to 10
● C. Greater than 10
● D. Error

Which of the following is NOT a comparison operator in Python?

● A. ==
● B. !=
● C. <>
● D. <=

Which of the following Boolean expressions evaluates to False?

● A. 10 > 5 and 5 < 10


● B. 10 == 10 or 5 > 10
● C. not (10 > 5)
● D. 10 >= 5 and 5 <= 10

Which statement about the if statement in Python is TRUE?

● A. The if statement must always be followed by an else statement


● B. The if statement can be used alone without else or elif
● C. The if statement can only be used with numeric comparisons
● D. The if statement cannot contain Boolean expressions

What is the output of the following code snippet?

x=5
if x > 10:
print("Greater than 10")
else:
print("10 or less")

● A. Greater than 10
● B. 10 or less
● C. Error
● D. None

Which of the following code snippets correctly uses an elif statement?


A.
if x < 10:
print("Less than 10")
else if x == 10:
print("Equal to 10")

B.
if x < 10:
print("Less than 10")
elif x == 10:
print("Equal to 10")
else:
print("Greater than 10")

C.
if x < 10:
print("Less than 10")
elif x == 10:
print("Greater than 10")
else:
print("Equal to 10")

D.
if x < 10:
print("Less than 10")
elif x == 10
print("Equal to 10")
else:
print("Greater than 10")

Which of the following statements about nested if statements is FALSE?

● A. Nested if statements allow for checking multiple conditions


● B. Nested if statements can only have one level of nesting
● C. Nested if statements can contain other if or elif statements
● D. Nested if statements must be properly indented

What will be the output of the following code?

x = 10
y=5
if x > y:
if x == 10:
print("x is 10")
else:
print("x is greater than 10")
else:
print("x is less than or equal to y")

● A. x is 10
● B. x is greater than 10
● C. x is less than or equal to y
● D. Error

Which of the following best describes the purpose of the elif keyword in Python?

● A. To end an if block
● B. To provide an alternative condition if the initial if statement is false
● C. To indicate the end of a loop
● D. To execute a block of code when the initial if statement is true

Which of the following will raise a SyntaxError?

A.
if x > 10:
print("Greater than 10")

B.
if x > 10:
print("Greater than 10")

C.
if x > 10:
print("Greater than 10")
else:
print("10 or less")
D.
if x > 10:
print("Greater than 10")
else if x == 10:
print("Equal to 10")
What will be the output of the following code?

x = 15
if x < 10:
print("Less than 10")
elif x < 20:
print("Less than 20")
else:
print("20 or more")

● A. Less than 10
● B. Less than 20
● C. 20 or more
● D. Error

Which of the following is true about the else statement in Python?

● A. It must follow an if or elif block


● B. It can be used alone
● C. It must contain a condition
● D. It can precede an if block

What will be the result of the following code?

x=5
if x == 5:
print("Equal to 5")
elif x == 10:
print("Equal to 10")
else:
print("Not equal to 5 or 10")

● A. Equal to 5
● B. Equal to 10
● C. Not equal to 5 or 10
● D. Error

What is the purpose of the pass statement in Python?


● A. To end a loop prematurely
● B. To do nothing and continue execution
● C. To raise an exception
● D. To exit a function

Which of the following is NOT a valid use of an if statement in Python?


A.
if x > 10:
print("Greater than 10")

B.
if x > 10:
print("Greater than 10")
else:
print("10 or less")

C.
if x > 10:
print("Greater than 10")
else if x == 10:
print("Equal to 10")

D.
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("10 or less")

What will be the output of the following code?

x = 20
if x < 10:
print("Less than 10")
elif x < 30:
print("Less than 30")
elif x < 40:
print("Less than 40")
else:
print("40 or more")
● A. Less than 10
● B. Less than 30
● C. Less than 40
● D. 40 or more

Which of the following statements about conditional statements is FALSE?

● A. Conditional statements can contain other conditional statements


● B. Conditional statements can evaluate expressions that return True or False
● C. Conditional statements can only be used with numeric data types
● D. Conditional statements must be properly indented

Which of the following is a valid example of a nested if statement?


A.
if x > 10:
if x < 20:
print("Between 10 and 20")

B.
if x > 10:
if x < 20:
print("Between 10 and 20")
else:
print("Greater than 20")
else:
print("10 or less")

C.
if x > 10:
if x < 20:
print("Between 10 and 20")
elif x == 20:
print("Equal to 20")
else:
print("Greater than 20")
else:
print("10 or less")

D. All of the above


Which of the following will result in an error?

A.
if x > 10:
print("Greater than 10")

B.
if x > 10:
print("Greater than 10")
else:
print("10 or less")

C.
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("10 or less")

D. None of the above

What will be the result of the following code?

x = 25
if x < 10:
print("Less than 10")
elif x < 20:
print("Less than 20")
else:
print("20 or more")

● A. Less than 10
● B. Less than 20
● C. 20 or more
● D. Error

Which of the following correctly describes an if-elif-else structure?

● A. It allows for multiple conditions to be checked sequentially


● B. It can only have one elif statement
● C. It must always end with an else statement
● D. It cannot contain any other if statements

What will be the output of the following code?

x = 30
if x < 20:
print("Less than 20")
elif x < 40:
print("Less than 40")
else:
print("40 or more")

● A. Less than 20
● B. Less than 40
● C. 40 or more
● D. Error

Which of the following statements is used to create a block of code in Python?

● A. Curly braces {}
● B. Parentheses ()
● C. Indentation
● D. Semicolons ;

Which of the following will raise a TypeError?

A.
if "string":
print("True")

B.
if 5 > 3:
print("True")

C. if [1, 2, 3]:
print("True")

D. None of the above

Which of the following statements about the pass statement is TRUE?


● A. It raises an exception
● B. It terminates the program
● C. It is used to create an empty block
● D. It returns a value

What will be the output of the following code?

x = 10
if x > 5:
pass
else:
print("x is less than or equal to 5")

● A. x is less than or equal to 5


● B. Nothing
● C. Error
● D. None

Which of the following is a valid use of the not operator in Python?

A.
if not True:
print("False")

B.
if not (5 > 10):
print("True")

C.
if not x:
print("Not x")

D. All of the above

Which of the following will NOT raise an error?

A.
if x = 10:
print("x is 10")
B.
if x == 10:
print("x is 10")
C.
if x => 10:
print("x is greater than or equal to 10")
D.
if x <> 10:
print("x is not equal to 10")

What will be the result of the following code?

x = 10
y = 20
if x < y and y < 30:
print("x is less than y and y is less than 30")
else:
print("Condition not met")

● A. x is less than y and y is less than 30


● B. Condition not met
● C. Error
● D. None

Which of the following statements about the elif statement is FALSE?

● A. It must follow an if statement


● B. It must contain a condition
● C. It can be used alone without an if statement
● D. It can be used multiple times in an if-elif-else structure

What will be the output of the following code?

x = 50
if x < 20:
print("Less than 20")
elif x < 40:
print("Less than 40")
elif x < 60:
print("Less than 60")
else:
print("60 or more")
● A. Less than 20
● B. Less than 40
● C. Less than 60
● D. 60 or more

Which of the following statements is true about the else block?

● A. It must always be used with an if statement


● B. It can be used alone without an if statement
● C. It executes when the if condition is True
● D. It executes when the if condition is False

Which of the following correctly describes the use of Boolean operators in Python?

● A. and returns True if both operands are true


● B. or returns True if both operands are true
● C. not returns True if the operand is true
● D. and returns True if at least one operand is true

What will be the output of the following code?

x=5
if x > 10:
print("Greater than 10")
elif x > 5:
print("Greater than 5")
else:
print("5 or less")

● A. Greater than 10
● B. Greater than 5
● C. 5 or less
● D. Error

Which of the following will raise a NameError?

A.
if x > 10:
print("Greater than 10")
B.
if 5 > 10:
print("True")
else:
print("False")

C.
if "string":
print("True")

D. None of the above

Which of the following is NOT a valid use of the if statement?

A.
if x:
print("x is True")

B.
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("10 or less")

C.
if x = 10:
print("x is 10")

D.
if not x:
print("Not x")

Which of the following statements about indentation in Python is FALSE?

● A. Indentation is used to define the scope of code blocks


● B. Indentation is optional and can be skipped
● C. Improper indentation can lead to IndentationError
● D. Indentation makes the code more readable
What will be the output of the following code?

x = 10
if x >= 10:
print("Greater than or equal to 10")
if x > 5:
print("Greater than 5")
else:
print("5 or less")

● A. Greater than or equal to 10


● B. Greater than or equal to 10 Greater than 5
● C. Greater than or equal to 10 5 or less
● D. Greater than 5

=====================================================================

CHAPTER 6

Which of the following best describes a condition-controlled loop?

● A. A loop that repeats a specific number of times


● B. A loop that repeats as long as a certain condition is true
● C. A loop that has no end
● D. A loop that only runs once

Which keyword is used to create a loop that repeats as long as a condition is true?

● A. for
● B. while
● C. loop
● D. repeat

In Python, what will the following code output?

i=0
while i < 3:
print(i)
i += 1
● A. 0 1 2
● B. 1 2 3
● C. 0 1 2 3
● D. 1 2

What will be the output of the following code snippet?

for i in range(1, 5):


print(i)

● A. 0 1 2 3 4
● B. 1 2 3 4 5
● C. 1 2 3 4
● D. 2 3 4 5

Which loop is used when the number of iterations is known beforehand?

● A. while
● B. for
● C. infinite
● D. sentinel

What is the output of the following code?

for i in range(5, 1, -1):


print(i)

● A. 5 4 3 2 1
● B. 5 4 3 2
● C. 4 3 2 1
● D. 5 4 3

Which statement is used to exit a loop prematurely in Python?

● A. exit
● B. stop
● C. break
● D. terminate

What is the purpose of the continue statement in a loop?

● A. To end the loop


● B. To skip the rest of the code inside the loop for the current iteration
● C. To exit the loop and continue with the next iteration
● D. To reset the loop counter

What will be the result of the following code?

i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)

● A. 1 2 3 4 5
● B. 1 2 4 5
● C. 0 1 2 4 5
● D. 1 2 3 4

Which of the following loops is an example of a count-controlled loop?

A.
while x < 10:
print(x)
x += 1

B.
for x in range(10):
print(x)

C.
while True:
if x == 10:
break
print(x)
x += 1

D.
for x in [1, 2, 3, 4, 5]:
print(x)
What is the output of the following code snippet?

for i in range(1, 10, 2):


print(i, end=' ')

● A. 1 3 5 7 9
● B. 2 4 6 8 10
● C. 1 3 5 7 9 11
● D. 0 2 4 6 8

What will be the output of the following code?

x = 10
while x > 0:
print(x)
x -= 2

● A. 10 8 6 4 2 0
● B. 8 6 4 2 0
● C. 10 8 6 4 2
● D. 10 9 8 7 6 5 4 3 2 1

Which of the following best describes a sentinel-controlled loop?

● A. A loop that repeats a specific number of times


● B. A loop that repeats until a special value is encountered
● C. A loop that always executes at least once
● D. A loop that never ends

What will be the result of the following code?

total = 0
num = 0
while num >= 0:
num = int(input("Enter a non-negative integer (negative to end series): "))
if num >= 0:
total += num
print("Sum total of the series:", total)
● A. It will prompt the user until a negative number is entered and print the sum of all
non-negative numbers entered.
● B. It will print the sum of all numbers entered including the negative number.
● C. It will run indefinitely.
● D. It will print an error because the loop never ends.

Which of the following is NOT a characteristic of an infinite loop?

● A. It never stops running.


● B. It always includes a break statement.
● C. It may be caused by a logical error.
● D. It can be terminated manually.

What is the output of the following code?

i=0
while i < 3:
print(i)
i += 1
else:
print("Done")

● A. 0 1 2
● B. 0 1 2 Done
● C. Done
● D. 1 2 3 Done

In which scenario would you use a for loop instead of a while loop?

● A. When you need to repeat a block of code an unknown number of times.


● B. When you need to iterate over a sequence of elements.
● C. When you want to create an infinite loop.
● D. When you want to execute the loop at least once.

Which of the following statements is true about nested loops?

● A. Only for loops can be nested.


● B. You can only nest two loops.
● C. Any type of loop can be nested inside another loop.
● D. Nested loops must have the same type.
What will be the output of the following code?

for i in range(3):
for j in range(2):
print(i, j)

● A. 0 0 0 1 1 0 1 1 2 0 2 1
● B. 0 1 1 0 2 1 2 0 3 1
● C. 0 0 0 1 1 0 1 1 2 0 2 1 3 0 3 1
● D. 0 0 1 0 1 1 2 0 2 1

What is the purpose of the break statement in a nested loop?

● A. To exit the innermost loop only


● B. To exit all loops
● C. To skip the current iteration and continue with the next one
● D. To reset the loop counter

Which of the following will cause an infinite loop?

A.
i=0
while i < 5:
print(i)
i += 1

B.
for i in range(10):
print(i)

C.
i=0
while i < 5:
print(i)

D.
for i in [1, 2, 3]:
print(i)
What is the output of the following code snippet?

for i in range(2):
for j in range(2):
if i == j:
break
print(i, j)

● A. 0 0 1 1
● B. 0 1 1 0
● C. 1 0
● D. 0 1

Which statement will skip the rest of the code inside the loop for the current iteration and
continue with the next iteration?

● A. break
● B. exit
● C. continue
● D. pass

What will be the output of the following code?

count = 0
while count < 5:
count += 1
if count == 3:
break
print(count)

● A. 1 2
● B. 1 2 3
● C. 1 2 4 5
● D. 1 2 3 4 5

Which of the following describes a for loop with a range?

● A. A loop that iterates over each character in a string


● B. A loop that iterates over a sequence of numbers generated by the range() function
● C. A loop that executes a block of code as long as a condition is true
● D. A loop that executes a block of code for each item in a list

What is the output of the following code?

for i in range(2, 10, 2):


print(i, end=' ')

● A. 2 4 6 8 10
● B. 2 4 6 8
● C. 0 2 4 6 8 10
● D. 2 3 4 5 6 7 8 9

Which of the following best describes a pre-test loop?

● A. The loop body is executed at least once before the condition is tested.
● B. The loop condition is tested before the loop body is executed.
● C. The loop executes an infinite number of times.
● D. The loop condition is tested after the loop body is executed.

What will be the output of the following code?

i = 10
while i > 0:
print(i, end=' ')
i -= 3

● A. 10 7 4 1 -2
● B. 10 8 6 4 2
● C. 10 7 4 1
● D. 10 7 4 1 -2

What is the purpose of the else clause in a loop?

● A. To execute a block of code when the loop is infinite


● B. To execute a block of code when the loop condition becomes False
● C. To execute a block of code before the loop starts
● D. To execute a block of code if the loop condition is True

Which of the following loops will execute at least once, even if the condition is initially False?

● A. Pre-test loop
● B. Post-test loop
● C. Infinite loop
● D. Sentinel loop

What will be the output of the following code?

total = 0
for i in range(1, 5):
total += i
print(total)

● A. 5
● B. 10
● C. 15
● D. 20

Which of the following best describes a nested loop?

● A. A loop that runs forever


● B. A loop that runs multiple times
● C. A loop that contains another loop inside it
● D. A loop that is controlled by a condition

What will be the output of the following code?

n=5
while n > 0:
n -= 1
print(n)

● A. 5 4 3 2 1 0
● B. 4 3 2 1 0
● C. 4 3 2 1
● D. 5 4 3 2 1

Which of the following best describes the use of the range() function in a for loop?

● A. To create an infinite loop


● B. To generate a sequence of numbers for iteration
● C. To break out of the loop
● D. To skip the current iteration

Which of the following will NOT raise an error?

A.
for i in range('a', 'z'):
print(i)

B.
for i in range(10, 1, -1):
print(i)

C.
for i in 10:
print(i)

D.
for i in [10, 20, 30]:
print(i)

What will be the output of the following code?

i=1
while i <= 3:
print(i)
i=i+1

● A. 1 2 3
● B. 0 1 2 3
● C. 2 3 4
● D. 1 2 3 4

Which of the following best describes an infinite loop?

● A. A loop that runs a fixed number of times


● B. A loop that contains another loop inside it
● C. A loop that runs indefinitely without stopping
● D. A loop that runs at least once
What is the purpose of the pass statement in a loop?

● A. To exit the loop


● B. To skip the rest of the code inside the loop for the current iteration only
● C. To do nothing and continue with the next iteration
● D. To raise an exception

Which of the following is an example of a nested loop?

A.
for i in range(3):
print(i)

B.
while i < 5:
print(i)
i += 1

C.
for i in range(3):
for j in range(2):
print(i, j)

D.
while i < 5:
print(i)
i=i+1

What will be the output of the following code?

for i in range(3):
for j in range(2):
if j == 1:
break
print(i, j)

● A. 0 0 1 0 2 0
● B. 0 1 1 1 2 1
● C. 0 0 0 1 1 0 1 1 2 0 2 1
● D. 0 0 1 0 2 0

=====================================================================

CHAPTER 7

Which keyword is used to define a function in Python?

● A. func
● B. def
● C. function
● D. define

What is the output of the following code?

def greet():
print("Hello, World!")

greet()

● A. Hello, World!
● B. Error
● C. greet()
● D. None

Which of the following is a valid function definition?

● A. def myFunction():
● B. def myFunction:
● C. function myFunction()
● D. def myFunction()

What will be the output of the following code?

def add(a, b):


return a + b

result = add(3, 4)
print(result)
● A. 34
● B. 7
● C. Error
● D. 12

Which statement about functions in Python is FALSE?

● A. Functions can return values


● B. Functions can have default parameter values
● C. Functions can be called before they are defined
● D. Functions can take multiple arguments

What is the purpose of the return statement in a function?

● A. To terminate the function execution


● B. To pass control back to the caller
● C. To return a value to the caller
● D. All of the above

What will be the output of the following code?

def multiply(x, y=2):


return x * y

print(multiply(5))

● A. 10
● B. 25
● C. Error
● D. 5

Which of the following is a built-in function in Python?

● A. def
● B. return
● C. print
● D. func

What will be the output of the following code?

def say_hello(name):
print("Hello, " + name)
say_hello("Alice")

● A. Hello,
● B. Hello, Alice
● C. Error
● D. name

Which of the following is true about default parameter values in functions?

● A. They must be defined first in the parameter list


● B. They must be defined last in the parameter list
● C. They can be defined anywhere in the parameter list
● D. They cannot be used in functions

What will be the output of the following code?

def func(a, b=4, c=5):


print(a, b, c)

func(2, c=8)

● A. 2 4 5
● B. 2 8 5
● C. 2 4 8
● D. 2 8 8

Which of the following best describes a function that does not return a value?

● A. Fruitful function
● B. Void function
● C. Built-in function
● D. User-defined function

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

● A. type()
● B. float()
● C. int()
● D. add()
What will be the output of the following code?

def func(a, b):


return a + b

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

● A. 53
● B. 8
● C. Error
● D. 15

Which of the following is true about the def keyword in Python?

● A. It is used to call a function


● B. It is used to define a function
● C. It is used to import a module
● D. It is used to return a value from a function

What is the output of the following code?

def func():
return 3 + 4

print(func())

● A. 3 + 4
● B. 34
● C. 7
● D. Error

Which of the following statements about function parameters is FALSE?

● A. Parameters can have default values


● B. Parameters are mandatory in a function definition
● C. Parameters can be of any data type
● D. Parameters can be specified with keywords
What will be the output of the following code?

def func(a, b=2, c=3):


return a * b * c

print(func(4))

● A. 4
● B. 24
● C. 9
● D. 8

Which of the following is true about the return statement in Python?

● A. It can only return a single value


● B. It can return multiple values as a tuple
● C. It can only be used once in a function
● D. It is optional in a function

What will be the output of the following code?

def func(a, b):


return a * b

result = func(2, 3)
print(result)

● A. 6
● B. 23
● C. Error
● D. 5

Which of the following is true about user-defined functions in Python?

● A. They can only be called once


● B. They must return a value
● C. They can take any number of arguments
● D. They cannot use built-in functions
What will be the output of the following code?

def func(a, b=3):


return a + b

result = func(5, 2)
print(result)

● A. 7
● B. 5
● C. 8
● D. Error

Which of the following is true about the scope of variables in a function?

● A. Variables defined in a function are global


● B. Variables defined in a function are local to that function
● C. Variables defined in a function are accessible outside the function
● D. Variables defined in a function must be global

Which of the following statements is true about function calls in Python?

● A. Functions cannot call other functions


● B. Functions can call themselves
● C. Functions cannot take other functions as arguments
● D. Functions cannot return other functions

What will be the output of the following code?

def add(a, b):


return a + b

def multiply(x, y):


return x * y

result = multiply(add(2, 3), 4)


print(result)

● A. 20
● B. 14
● C. 10
● D. 24

Which of the following best describes the use of *args in a function definition?

● A. To accept a fixed number of arguments


● B. To accept a variable number of keyword arguments
● C. To accept a variable number of non-keyword arguments
● D. To accept no arguments

What will be the output of the following code?

def func(*args):
return sum(args)

print(func(1, 2, 3))

● A. 6
● B. 123
● C. Error
● D. None

Which of the following is true about the **kwargs parameter in Python functions?

● A. It allows passing a variable number of non-keyword arguments


● B. It allows passing a fixed number of keyword arguments
● C. It allows passing a variable number of keyword arguments
● D. It is not a valid parameter in Python

What will be the output of the following code?

def func(**kwargs):
for key, value in kwargs.items():
print(key, value)

func(a=1, b=2, c=3)

● A. a 1 b 2 c 3
● B. 1 2 3
● C. a b c
● D. Error

Which of the following best describes the use of default parameter values in functions?

● A. They must always be provided when calling the function


● B. They are optional and can be overridden by arguments
● C. They cannot be overridden by arguments
● D. They must be defined last in the parameter list

What will be the output of the following code?

def func(a, b=4):


return a * b

print(func(3))

● A. 12
● B. 7
● C. Error
● D. 3

Which of the following best describes the concept of "passing by reference" in Python?

● A. The actual object is passed to the function, and changes affect the original object
● B. A copy of the object is passed to the function, and changes do not affect the original
object
● C. The object's memory address is passed to the function
● D. The object cannot be changed within the function

What will be the output of the following code?

def func(a, b):


a += 1
b += 2
return a, b

result = func(3, 4)
print(result)

● A. 3 4
● B. 4 6
● C. 4 5
● D. 5 6

Which of the following is true about the return statement in a function?

● A. It can only return a single value


● B. It can return multiple values as a tuple
● C. It can only be used once in a function
● D. It is optional in a function

What will be the output of the following code?

def func(a, b=2):


return a + b

print(func(3, 4))

● A. 5
● B. 7
● C. Error
● D. None

Which of the following best describes a "fruitful" function in Python?

● A. A function that does not return a value


● B. A function that prints a value
● C. A function that returns a value
● D. A function that has no parameters

What will be the output of the following code?

def greet(name="World"):
return "Hello, " + name

print(greet("Alice"))

● A. Hello,
● B. Hello, World
● C. Hello, Alice
● D. Error

What will be the output of the following code?

def add(a, b):


return a + b

def multiply(x, y):


return x * y

result = multiply(add(1, 2), add(3, 4))


print(result)

● A. 7
● B. 21
● C. 12
● D. 14

=====================================================================

CHAPTER 8

Which of the following correctly initializes a string in Python?

● A. str = 'Hello'
● B. str = "Hello"
● C. str = """Hello"""
● D. All of the above

What is the result of the following code?

str1 = "Hello"
str2 = 'World'
result = str1 + str2
print(result)

● A. Hello World
● B. HelloWorld
● C. Error
● D. Hello+World
Which of the following will raise a TypeError?

● A. str1 = '123' + '456'


● B. str1 = '123' + 456
● C. str1 = '123' * 3
● D. str1 = 3 * '123'

How do you include a single quote inside a single-quoted string?

● A. str = 'It\'s a test'


● B. str = 'It's a test'
● C. str = "It's a test"
● D. Both A and C

What will be the output of the following code?

str = "Hello World"


print(str[0])

● A. H
● B. e
● C. o
● D. Error

Which method is used to find the first occurrence of a substring in a string?

● A. str.find()
● B. str.index()
● C. str.count()
● D. str.search()

What is the output of the following code?

str = "banana"
print(str.find('na'))

● A. 1
● B. 2
● C. 3
● D. 4
Which of the following will result in a TypeError?

● A. int('123')
● B. float('123.45')
● C. str(123)
● D. int('abc')

How can you access the last character of a string str?

● A. str[-1]
● B. str[len(str)]
● C. str[len(str)-1]
● D. Both A and C

What will be the result of the following code?

str = "Python"
print(str[:3])

● A. Pyt
● B. hon
● C. tho
● D. Error

Which of the following methods returns the length of a string?

● A. str.size()
● B. str.length()
● C. len(str)
● D. size(str)

Which operator can be used to repeat a string multiple times?

● A. +
● B. *
● C. %
● D. //

What is the output of the following code?

str = "Hello"
print(str * 2)
● A. HelloHello
● B. Hello Hello
● C. Hello2
● D. Error

Which of the following is a valid way to concatenate strings?

● A. 'Hello' + ' ' + 'World'


● B. 'Hello'.concat('World')
● C. 'Hello'.join('World')
● D. 'Hello' 'World'

Which method converts all characters of a string to uppercase?

● A. str.upper()
● B. str.capitalize()
● C. str.toUpperCase()
● D. str.uppercase()

What will be the output of the following code?

str = "Python Programming"


print(str.lower())

● A. python programming
● B. Python programming
● C. PYTHON PROGRAMMING
● D. Error

Which of the following will check if a string str contains only digits?

● A. str.isdigit()
● B. str.isnumeric()
● C. str.isdecimal()
● D. All of the above

What is the output of the following code?

str = " Hello World "


print(str.strip())
● A. Hello World
● B. Hello World
● C. Hello
● D. World

Which method checks if a string starts with a specified prefix?

● A. str.startswith()
● B. str.startswith(prefix)
● C. str.startsWith(prefix)
● D. str.beginWith(prefix)

What will be the result of the following code?

str = "Hello"
str[0] = 'h'
print(str)

● A. hello
● B. hHello
● C. Error
● D. Hello

Which method is used to replace a substring within a string?

● A. str.replace()
● B. str.replace(old, new)
● C. str.replace(old, new, count)
● D. Both B and C

What will be the output of the following code?

str = "abc abc abc"


print(str.replace('a', 'x', 2))

● A. xbc xbc xbc


● B. xbc abc abc
● C. abc xbc abc
● D. xbc xbc abc
Which method returns a string where all occurrences of a specified value are replaced with
another specified value?

● A. str.swapcase()
● B. str.replace()
● C. str.join()
● D. str.translate()

How can you convert a string to a list of characters?

● A. list(str)
● B. str.split()
● C. str.toList()
● D. listOf(str)

What is the output of the following code?

str = "Python"
print(str[::-1])

● A. nohtyP
● B. Python
● C. nohtyP Python
● D. Error

Which method checks if all characters in the string are alphabetic?

● A. str.isalpha()
● B. str.isalnum()
● C. str.isdigit()
● D. str.isnumeric()

What is the output of the following code?

str = "Python"
print(str[1:4])

● A. Pyt
● B. yth
● C. ytho
● D. ytho
Which of the following will raise an error?

● A. str = "Python"[3]
● B. str = "Python"[3:]
● C. str = "Python"[:3]
● D. str = "Python"[3:100]

What will be the output of the following code?

str = "Python"
print(str[2:])

● A. Py
● B. Python
● C. thon
● D. Pyt

Which method would you use to check if a string contains only whitespace characters?

● A. str.isempty()
● B. str.iswhitespace()
● C. str.isspace()
● D. str.isblank()

What is the output of the following code?

str = "hello"
print(str.capitalize())

● A. hello
● B. Hello
● C. HELLO
● D. Error

Which method splits a string into a list where each word is a list item?

● A. str.split()
● B. str.join()
● C. str.partition()
● D. str.separate()
What will be the output of the following code?

str = "Hello, World!"


print(str.split(','))

● A. ['Hello', ' World!']


● B. ['Hello, World!']
● C. ['Hello', 'World!']
● D. Error

Which method returns the lowest index in the string where substring sub is found?

● A. str.index(sub)
● B. str.find(sub)
● C. str.rindex(sub)
● D. Both A and B

What is the output of the following code?

str = "Hello"
print(str * 2)

● A. HelloHello
● B. Hello Hello
● C. Hello2
● D. Error

Which method converts all uppercase letters in a string to lowercase?

● A. str.lower()
● B. str.upper()
● C. str.title()
● D. str.capitalize()

What is the output of the following code?

str = " Hello World "


print(str.lstrip())

● A. Hello World
● B. Hello World
● C. Hello World
● D. World

Which of the following methods can be used to check if a string ends with a specified suffix?

● A. str.endswith(suffix)
● B. str.end(suffix)
● C. str.endsWith(suffix)
● D. str.finishWith(suffix)

What will be the result of the following code?

str = "Python"
print(str[3:6])

● A. Pyt
● B. hon
● C. tho
● D. yth

Which method returns a string where all occurrences of a specified value are replaced with
another specified value?

● A. str.swapcase()
● B. str.replace()
● C. str.join()
● D. str.translate()

=====================================================================
CHAPTER 9

Which of the following correctly initializes an empty list in Python?

● A. list = ()
● B. list = []
● C. list = {}
● D. list = list()

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
print(list[2])

● A. 1
● B. 2
● C. 3
● D. 4

Which of the following will raise an IndexError?

● A. list = [1, 2, 3]; print(list[1])


● B. list = [1, 2, 3]; print(list[-1])
● C. list = [1, 2, 3]; print(list[3])
● D. list = [1, 2, 3]; print(list[0])

What is the output of the following code?

list = [1, 2, 3, 4, 5]
list.append(6)
print(list)

● A. [1, 2, 3, 4, 5, 6]
● B. [1, 2, 3, 4, 5]
● C. [6, 1, 2, 3, 4, 5]
● D. Error

How can you create a list containing the numbers 1 to 5?

● A. list = range(1, 5)
● B. list = [1, 2, 3, 4, 5]
● C. list = list(1, 2, 3, 4, 5)
● D. list = (1, 2, 3, 4, 5)

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
list.insert(2, 'a')
print(list)

● A. [1, 2, 'a', 3, 4, 5]
● B. [1, 'a', 2, 3, 4, 5]
● C. [1, 2, 3, 4, 5, 'a']
● D. Error

Which of the following statements is TRUE about lists in Python?

● A. Lists are immutable.


● B. Lists can contain elements of different types.
● C. Lists are always sorted.
● D. Lists cannot contain other lists.

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
del list[1:3]
print(list)

● A. [1, 2, 3, 4, 5]
● B. [1, 4, 5]
● C. [1, 3, 4, 5]
● D. [1, 4, 3, 5]

Which of the following will raise a TypeError?

● A. list = [1, 2, 3] + [4, 5, 6]


● B. list = [1, 2, 3] + 4
● C. list = [1, 2, 3] * 2
● D. list = 2 * [1, 2, 3]

What is the output of the following code?

list = [1, 2, 3, 4, 5]
print(list[-1])

● A. 1
● B. 2
● C. 4
● D. 5

Which method would you use to add multiple elements to the end of a list?

● A. list.append([6, 7])
● B. list.insert(6, 7)
● C. list.extend([6, 7])
● D. list.add([6, 7])

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
list.extend([6, 7, 8])
print(list)

● A. [1, 2, 3, 4, 5, [6, 7, 8]]


● B. [1, 2, 3, 4, 5, 6, 7, 8]
● C. [1, 2, 3, 4, 5, 6, 7]
● D. Error

What is the output of the following code?

list = [1, 2, 3, 4, 5]
list.remove(3)
print(list)

● A. [1, 2, 4, 5]
● B. [1, 2, 3, 4, 5]
● C. [1, 4, 5]
● D. Error

Which method would you use to find the number of occurrences of an element in a list?

● A. list.index()
● B. list.count()
● C. list.find()
● D. list.search()

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
print(list.index(3))

● A. 2
● B. 3
● C. 4
● D. Error

Which of the following statements is TRUE about the len() function?

● A. len() returns the size of an object.


● B. len() returns the length of a string only.
● C. len() cannot be used with lists.
● D. len() is used to find the maximum value in a list.

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
print(len(list))

● A. 4
● B. 5
● C. 6
● D. Error

Which method reverses the elements of a list in place?

● A. list.reverse()
● B. list[::-1]
● C. list.reversed()
● D. list.sort(reverse=True)

What is the output of the following code?

list = [1, 2, 3, 4, 5]
list.reverse()
print(list)

● A. [5, 4, 3, 2, 1]
● B. [1, 2, 3, 4, 5]
● C. [1, 2, 3]
● D. Error

Which method sorts the elements of a list in ascending order?


● A. list.sorted()
● B. list.sort()
● C. list.order()
● D. list.arrange()

What will be the output of the following code?

list = [3, 1, 4, 1, 5, 9]
list.sort()
print(list)

● A. [9, 5, 4, 3, 1, 1]
● B. [1, 1, 3, 4, 5, 9]
● C. [3, 1, 4, 1, 5, 9]
● D. Error

What is the result of the following code?

list = [1, 2, 3]
list[1:2] = [4, 5]
print(list)

● A. [1, 4, 5, 2, 3]
● B. [1, 4, 5, 3]
● C. [1, 2, 4, 5, 3]
● D. [1, 4, 5]

Which of the following methods would you use to clear all elements from a list?

● A. list.clear()
● B. list.remove()
● C. list.delete()
● D. list.empty()

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
list.clear()
print(list)
● A. [1, 2, 3, 4, 5]
● B. []
● C. [None]
● D. Error

Which of the following will create a copy of a list?

● A. list.copy()
● B. list[:]
● C. list.copy(list)
● D. Both A and B

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
list_copy = list[:]
list_copy[0] = 99
print(list)

● A. [1, 2, 3, 4, 5]
● B. [99, 2, 3, 4, 5]
● C. [99, 2, 3, 4, 5, 1, 2, 3, 4, 5]
● D. Error

Which method can be used to add an element at a specific position in a list?

● A. list.add(index, element)
● B. list.insert(index, element)
● C. list.append(index, element)
● D. list.push(index, element)

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
list.insert(3, 'a')
print(list)

● A. [1, 2, 3, 'a', 4, 5]
● B. [1, 2, 'a', 3, 4, 5]
● C. [1, 'a', 2, 3, 4, 5]
● D. Error

Which of the following statements is TRUE about list slicing?

● A. List slicing creates a new list.


● B. List slicing modifies the original list.
● C. List slicing can only be done with positive indices.
● D. List slicing can only be done with negative indices.

What is the result of the following code?

list = [1, 2, 3, 4, 5]
print(list[1:4])

● A. [1, 2, 3]
● B. [2, 3, 4]
● C. [2, 3]
● D. [3, 4, 5]

Which of the following will concatenate two lists?

● A. list1 + list2
● B. list1.append(list2)
● C. list1.insert(list2)
● D. list1.add(list2)

What will be the output of the following code?

list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)

● A. [1, 2, 3, 4, 5, 6]
● B. [1, 2, 3, [4, 5, 6]]
● C. [[1, 2, 3], [4, 5, 6]]
● D. Error

Which method returns a shallow copy of the list?

● A. list.copy()
● B. list.shallow()
● C. list.clone()
● D. list.duplicate()

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
new_list = list.copy()
new_list[0] = 10
print(list)

● A. [1, 2, 3, 4, 5]
● B. [10, 2, 3, 4, 5]
● C. [10, 1, 2, 3, 4, 5]
● D. Error

Which method can be used to combine the elements of two lists into one?

● A. list.append()
● B. list.extend()
● C. list.add()
● D. list.join()

What will be the output of the following code?

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)

● A. [1, 2, 3, 4, 5, 6]
● B. [1, 2, 3, [4, 5, 6]]
● C. [[1, 2, 3], [4, 5, 6]]
● D. Error

Which of the following is TRUE about list comprehensions?

● A. List comprehensions are slower than for loops.


● B. List comprehensions can be used to create new lists from existing lists.
● C. List comprehensions cannot be nested.
● D. List comprehensions cannot contain if conditions.
What is the result of the following code?

list = [1, 2, 3, 4, 5]
new_list = [x*2 for x in list]
print(new_list)

● A. [2, 4, 6, 8, 10]
● B. [1, 4, 9, 16, 25]
● C. [1, 2, 3, 4, 5]
● D. Error

Which of the following will correctly iterate over a list and print each element?

● A. for i in range(len(list)): print(list[i])


● B. for i in list: print(i)
● C. for i in list: print(list[i])
● D. Both A and B

What will be the output of the following code?

list = [1, 2, 3, 4, 5]
for i in range(len(list)):
list[i] += 1
print(list)

● A. [1, 2, 3, 4, 5]
● B. [2, 3, 4, 5, 6]
● C. [0, 1, 2, 3, 4]
● D. Error

=====================================================================

CHAPTER 10

Which of the following is a correct way to create a tuple?

● A. tuple = [1, 2, 3]
● B. tuple = {1, 2, 3}
● C. tuple = (1, 2, 3)
● D. tuple = <1, 2, 3>
What will be the output of the following code?

fruits = ("Apple", "Banana", "Cherry")


print(fruits[1])

● A. Apple
● B. Banana
● C. Cherry
● D. Error

Which of the following operations is NOT allowed on a tuple?

● A. tuple[1] = 4
● B. tuple[1:3]
● C. len(tuple)
● D. tuple.index(2)

How can you create an empty set in Python?

● A. set = {}
● B. set = ()
● C. set = set()
● D. set = []

What is the result of the following code?

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2)

● A. {1, 2, 3, 4, 5}
● B. {3}
● C. {1, 2, 4, 5}
● D. {}

Which of the following statements is TRUE about sets in Python?

● A. Sets can contain duplicate elements.


● B. Sets are ordered.
● C. Sets are immutable.
● D. Sets are unordered.
What will be the output of the following code?

set1 = {1, 2, 3}
set1.add(4)
print(set1)

● A. {1, 2, 3}
● B. {1, 2, 3, 4}
● C. {4, 1, 2, 3}
● D. Error

Which method is used to remove an element from a set without raising an error if the element is
not found?

● A. set.remove()
● B. set.discard()
● C. set.delete()
● D. set.pop()

What will be the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


print(dict['b'])

● A. 1
● B. 2
● C. 3
● D. Error

How can you create an empty dictionary in Python?

● A. dict = []
● B. dict = {}
● C. dict = ()
● D. dict = set()

Which of the following statements is TRUE about dictionaries in Python?

● A. Keys can be mutable.


● B. Values must be unique.
● C. Keys must be immutable.
● D. Dictionaries are ordered by default.

What will be the output of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


dict['d'] = 4
print(dict)

● A. {'a': 1, 'b': 2, 'c': 3}


● B. {'a': 1, 'b': 2, 'c': 3, 'd': 4}
● C. {'a': 1, 'b': 2, 'd': 4}
● D. Error

Which method would you use to get a list of all the keys in a dictionary?

● A. dict.keys()
● B. dict.values()
● C. dict.items()
● D. dict.get_keys()

What is the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


dict.pop('b')
print(dict)

● A. {'a': 1, 'b': 2, 'c': 3}


● B. {'a': 1, 'c': 3}
● C. {'a': 1, 'b': 2}
● D. Error

Which method is used to remove all elements from a dictionary?

● A. dict.clear()
● B. dict.delete_all()
● C. dict.remove()
● D. dict.discard()

What will be the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


print(dict.get('d', 'Not Found'))

● A. 1
● B. 2
● C. Not Found
● D. Error

Which of the following statements is TRUE about tuples in Python?

● A. Tuples are mutable.


● B. Tuples can contain elements of different types.
● C. Tuples are always sorted.
● D. Tuples cannot contain other tuples.

What will be the output of the following code?

fruits = ("Apple", "Banana", "Cherry")


print(fruits[1:3])

● A. ('Apple', 'Banana')
● B. ('Banana', 'Cherry')
● C. ('Apple', 'Cherry')
● D. ('Banana')

Which method is used to find the number of occurrences of an element in a tuple?

● A. tuple.index()
● B. tuple.count()
● C. tuple.find()
● D. tuple.search()

What will be the result of the following code?

fruits = ("Apple", "Banana", "Cherry")


print(fruits.index("Cherry"))

● A. 0
● B. 1
● C. 2
● D. Error
Which of the following is a valid way to create a set?

● A. set = {1, 2, 3}
● B. set = [1, 2, 3]
● C. set = (1, 2, 3)
● D. set = <1, 2, 3>

What will be the output of the following code?

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2)

● A. {1, 2, 3, 4, 5}
● B. {3}
● C. {1, 2, 4, 5}
● D. {}

Which of the following methods is used to create a shallow copy of a dictionary?

● A. dict.copy()
● B. dict.shallow()
● C. dict.clone()
● D. dict.duplicate()

What is the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


new_dict = dict.copy()
new_dict['a'] = 99
print(dict)

● A. {'a': 1, 'b': 2, 'c': 3}


● B. {'a': 99, 'b': 2, 'c': 3}
● C. {'a': 99, 'b': 2}
● D. {'b': 2, 'c': 3}

Which method is used to update a dictionary with key-value pairs from another dictionary?

● A. dict.update()
● B. dict.merge()
● C. dict.add()
● D. dict.extend()

What will be the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


dict.update({'d': 4, 'a': 0})
print(dict)

● A. {'a': 1, 'b': 2, 'c': 3, 'd': 4}


● B. {'a': 0, 'b': 2, 'c': 3, 'd': 4}
● C. {'a': 1, 'b': 2, 'd': 4}
● D. {'a': 0, 'd': 4}

Which method returns a view object of all the values in a dictionary?

● A. dict.keys()
● B. dict.values()
● C. dict.items()
● D. dict.get_values()

What will be the output of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


print(list(dict.values()))

● A. ['a', 'b', 'c']


● B. [1, 2, 3]
● C. ['a', 1, 'b', 2, 'c', 3]
● D. ['a', 1, 'b', 2]

What will be the output of the following code?

fruits = ("Apple", "Banana", "Cherry")


print(len(fruits))

● A. 2
● B. 3
● C. 4
● D. 5

Which method is used to add multiple elements to a set?

● A. set.add()
● B. set.update()
● C. set.append()
● D. set.insert()

What will be the result of the following code?

set1 = {1, 2, 3}
set1.update([4, 5, 6])
print(set1)

● A. {1, 2, 3, [4, 5, 6]}


● B. {1, 2, 3, 4, 5, 6}
● C. {4, 5, 6}
● D. Error

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

● A. set.remove()
● B. set.discard()
● C. set.pop()
● D. set.delete()

What will be the output of the following code?

set1 = {1, 2, 3}
set1.pop()
print(set1)

● A. {2, 3}
● B. {1, 3}
● C. {1, 2}
● D. Error

Which method is used to get a sorted list of all keys in a dictionary?

● A. dict.sort_keys()
● B. dict.sorted_keys()
● C. sorted(dict)
● D. dict.sort()

What will be the output of the following code?

dict = {'c': 3, 'a': 1, 'b': 2}


print(sorted(dict))

● A. {'a': 1, 'b': 2, 'c': 3}


● B. ['c', 'a', 'b']
● C. ['a', 'b', 'c']
● D. {'c': 3, 'b': 2, 'a': 1}

Which of the following is TRUE about dictionaries in Python?

● A. Dictionaries can have duplicate keys.


● B. Dictionaries are mutable.
● C. Dictionaries are ordered by default.
● D. Keys in dictionaries must be mutable.

What will be the result of the following code?

dict = {'a': 1, 'b': 2, 'c': 3}


print(dict.pop('a'))

● A. 1
● B. 2
● C. 3
● D. Error

Which of the following methods returns a new view of the dictionary's items (key, value pairs)?

● A. dict.keys()
● B. dict.values()
● C. dict.items()
● D. dict.get_items()

What will be the output of the following code?

fruits = ("Apple", "Banana", "Cherry")


for fruit in fruits:
print(fruit)

● A. Apple Banana Cherry


● B. ('Apple', 'Banana', 'Cherry')
● C. 'Apple' 'Banana' 'Cherry'
● D. Error

Which method is used to remove all items from a set?

● A. set.clear()
● B. set.remove_all()
● C. set.delete()
● D. set.discard()

=====================================================================

CHAPTER 11

Which mode is used to open a file for reading and writing, where the file is overwritten if it
already exists?

● A. r+
● B. w+
● C. a+
● D. x+

What will be the output of the following code?

file = open("sample.txt", "w")


file.write("Hello, World!")
file.close()
file = open("sample.txt", "r")
print(file.read())

● A. Hello, World!
● B. Error
● C. None
● D. Hello,
Which of the following is NOT a valid file mode in Python?

● A. rb
● B. rw
● C. wb
● D. ab

What does the following code do?

file = open("data.txt", "a")


file.write("New data\n")
file.close()

● A. Overwrites the file data.txt with "New data"


● B. Appends "New data" to the file data.txt
● C. Raises an error if data.txt does not exist
● D. Opens the file data.txt for reading

What is the result of the following code?

file = open("example.txt", "x")


file.write("This is an example.")
file.close()

● A. Creates a new file example.txt and writes "This is an example."


● B. Opens example.txt if it exists and writes "This is an example."
● C. Raises an error if example.txt already exists
● D. Reads the contents of example.txt

What will be the output of the following code?

file = open("test.txt", "w")


file.write("Test data")
file.close()
file = open("test.txt", "a")
file.write(" More data")
file.close()
file = open("test.txt", "r")
print(file.read())
● A. Test data More data
● B. Test data
● C. More data
● D. Error

Which method is used to read all lines of a file into a list?

● A. file.read()
● B. file.readlines()
● C. file.readline()
● D. file.read_all()

What is the purpose of the with statement when working with files in Python?

● A. To open multiple files at once


● B. To handle exceptions automatically
● C. To ensure that files are properly closed after their suite finishes
● D. To open a file in read-only mode

What will be the output of the following code?

with open("log.txt", "w") as file:


file.write("Log entry 1\n")
print(file.closed)

● A. False
● B. True
● C. None
● D. Error

Which of the following exceptions is raised when trying to open a non-existent file in read
mode?

● A. FileNotFoundError
● B. IOError
● C. EOFError
● D. OSError

What does the try block in exception handling do?

● A. Executes the code and raises an exception if there is an error


● B. Catches and handles the exception
● C. Executes the code regardless of an error
● D. Logs the exception without handling it

What will be the output of the following code?

try:
file = open("nonexistent.txt", "r")
except FileNotFoundError:
print("File not found.")

● A. Error
● B. File not found.
● C. None
● D. File cannot be opened.

Which method is used to remove whitespace from the end of a string?

● A. strip()
● B. lstrip()
● C. rstrip()
● D. remove()

What will be the result of the following code?

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


for line in file:
print(line.strip())

● A. Prints each line of data.txt without leading whitespace


● B. Prints each line of data.txt without trailing whitespace
● C. Prints each line of data.txt without any whitespace
● D. Raises an error if data.txt does not exist

Which of the following statements about binary files is TRUE?

● A. Binary files store data as ASCII or Unicode characters


● B. Binary files have a newline delimiter
● C. Binary files can only be read by a Python program
● D. Binary files are faster and easier for a program to read and write than text files
What will be the output of the following code?

file = open("binaryfile.bin", "wb")


file.write(b'\x00\xFF\x00\xFF')
file.close()
file = open("binaryfile.bin", "rb")
print(file.read())

● A. b'\x00\xFF\x00\xFF'
● B. \x00\xFF\x00\xFF
● C. 0000FFFF
● D. \x00FF\x00FF

Which file mode is used for both reading and writing without truncating the file?

● A. r
● B. w
● C. a
● D. r+

What is the purpose of the finally block in exception handling?

● A. To execute code only if there is an exception


● B. To execute code only if there is no exception
● C. To execute code regardless of whether an exception occurs
● D. To handle specific exceptions

What will be the output of the following code?

try:
file = open("data.txt", "r")
data = file.read()
finally:
file.close()
print(data)

● A. Contents of data.txt
● B. None
● C. Error
● D. File closed
Which method is used to write a list of strings to a file?

● A. file.write_lines()
● B. file.writelines()
● C. file.write_list()
● D. file.write()

What will be the result of the following code?

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


file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])

● A. Writes "Line 1\nLine 2\nLine 3\n" to output.txt


● B. Writes ['Line 1\n', 'Line 2\n', 'Line 3\n'] to output.txt
● C. Writes "Line 1Line 2Line 3" to output.txt
● D. Raises an error

What is the difference between try/except and try/finally blocks in Python?

● A. try/except handles exceptions, try/finally ensures code runs regardless of exceptions


● B. try/except ensures code runs regardless of exceptions, try/finally handles exceptions
● C. try/except handles only specific exceptions, try/finally handles all exceptions
● D. try/except must always be used with try/finally

Which method is used to read a file line by line in Python?

● A. file.read()
● B. file.readline()
● C. file.readlines()
● D. file.read_line_by_line()

What will be the output of the following code?

file = open("data.txt", "r")


for line in file:
if line.startswith("Important"):
print(line.strip())
file.close()

● A. Prints all lines in data.txt


● B. Prints lines that start with "Important" without leading whitespace
● C. Prints lines that start with "Important" without trailing whitespace
● D. Raises an error if data.txt does not exist

Which exception is raised for an invalid operation on a file?

● A. FileNotFoundError
● B. IOError
● C. OSError
● D. EOFError

What will be the output of the following code?

try:
file = open("example.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found.")
finally:
print("End of program.")

● A. File not found.


● B. Contents of example.txt followed by End of program.
● C. File not found. followed by End of program.
● D. Error

What is the purpose of the logging module in Python?

● A. To handle file operations


● B. To handle exceptions
● C. To log events and errors during program execution
● D. To read and write log files

What will be the output of the following code?

import logging

try:
print(10 / 0)
except ZeroDivisionError:
logging.error("Attempted to divide by zero.")
● A. Attempted to divide by zero.
● B. ZeroDivisionError
● C. Error
● D. No output

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

● A. ZeroDivisionError
● B. FileNotFoundError
● C. MemoryError
● D. InputError

What will be the result of the following code?

try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
data = "No data found."
finally:
print(data)

● A. No data found.
● B. Contents of data.txt
● C. Error
● D. None

Which method is used to append data to an existing file without truncating it?

● A. file.write()
● B. file.append()
● C. file.writelines()
● D. file.write_append()

What will be the result of the following code?

with open("numbers.txt", "w") as file:


file.write("123\n456\n789")
with open("numbers.txt", "a") as file:
file.write("\n101112")
with open("numbers.txt", "r") as file:
print(file.read())

● A. 123\n456\n789\n101112
● B. 123456789101112
● C. 123 456 789 101112
● D. Error

What is the purpose of the else block in exception handling?

● A. To execute code if an exception is raised


● B. To execute code if no exception is raised
● C. To execute code regardless of whether an exception is raised
● D. To execute code if multiple exceptions are raised

What will be the output of the following code?

try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("You entered:", num)

● A. Invalid input.
● B. You entered: <number>
● C. Error
● D. Both A and B

Which of the following statements is TRUE about exception handling in Python?

● A. The try block must be followed by an except block


● B. The try block must be followed by a finally block
● C. The try block can be followed by both except and finally blocks
● D. The try block cannot be followed by both except and finally blocks

Which method is used to read the entire contents of a file into a string?

● A. file.read()
● B. file.readline()
● C. file.readlines()
● D. file.read_all()
Which statement is used to skip the current iteration of a loop and continue with the next
iteration?

● A. break
● B. pass
● C. continue
● D. skip

What will be the result of the following code?

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


lines = file.readlines()
for line in lines:
if "Error" in line:
continue
print(line.strip())

● A. Prints all lines in data.txt


● B. Prints lines that contain "Error"
● C. Prints lines that do not contain "Error" without leading whitespace
● D. Raises an error if data.txt does not exist

What is the result of the following code?

try:
with open("output.txt", "w") as file:
file.write("Output data")
except Exception as e:
print("An error occurred:", e)

● A. Writes "Output data" to output.txt


● B. An error occurred:
● C. Error
● D. None

=====================================================================

You might also like