Exercise: Python

Questions for: Conditional Statements

Which of the following is the correct syntax for a while loop?
A:
while condition:
    # code block
B:
while (condition)
    # code block
C:
do while condition:
    # code block
D:
for condition in while:
    # code block
Answer: A
The correct syntax for a while loop in Python is to use the while keyword followed by a condition.
How can you iterate over both the index and the elements of a list in a for loop?
A:
Using for i in range(len(my_list))
B:
Using for element in my_list
C:
Using for i, element in enumerate(my_list)
D:
Using for i, element in range(len(my_list))
Answer: C
The enumerate() function is used to iterate over both the index and the elements of a list in a for loop.
What will be the output of the following code?
number = 15
result = "Even" if number % 2 == 0 else "Odd"
print(result)
A:
Even
B:
Odd
C:
Error
D:
No output
Answer: B
The code uses a conditional expression (if-else shorthand) to determine if number is even or odd. In this case, it is odd, so the result is "Odd."
Which of the following statements is used to raise a custom exception?
A:
assert
B:
throw
C:
raise
D:
custom
Answer: C
The raise statement is used to raise a custom exception in Python. You can use it to trigger a specific exception with a custom error message.
What is the purpose of the finally block in a try-except-finally statement?
A:
To handle exceptions
B:
To define the main body of the code
C:
To always execute code, whether an exception occurs or not
D:
To terminate the program
Answer: C

The finally block is used to define code that will be executed no matter what, whether an exception occurs in the try block or not.

This block is typically used for cleanup operations, such as closing files or releasing resources, that should be executed regardless of whether an exception was raised within the try block or not.

It ensures that certain actions are performed even if an exception occurs and is caught by an except block, or if no exception occurs at all.

Ad Slot (Above Pagination)
Quiz