Exercise: Python

Questions for: Conditional Statements

What will be the output of the following code?
value = True
result = "Yes" if value else "No"
print(result)
A:
Yes
B:
No
C:
True
D:
False
Answer: A
The code uses a conditional expression to assign "Yes" to the variable result if value is True, otherwise it assigns "No."
What does the with statement in Python primarily facilitate?
A:
Exception handling
B:
File handling and resource management
C:
Loop control
D:
Conditional statements
Answer: B
The with statement in Python is primarily used for file handling and resource management. It ensures that resources are properly managed, and it simplifies the code for tasks like file handling.
Which of the following is the correct syntax for a nested if statement?
A:
if condition1:
    if condition2:
        # code block
B:
if condition1:
    else:
        # code block
C:
if condition1:
    elif condition2:
        # code block
D:
if condition1:
    then condition2:
        # code block
Answer: A
The correct syntax for a nested if statement is to use multiple if statements inside each other.
What is the purpose of the is keyword?
A:
Checks for equality
B:
Checks for inequality
C:
Tests object identity
D:
Performs mathematical operations
Answer: C
The is keyword in Python is used to test if two variables refer to the same object in memory, checking object identity.
What does the else block in a try-except-else statement execute?
A:
It always executes, regardless of whether an exception occurs or not.
B:
It executes only if an exception is raised in the try block.
C:
It executes only if no exception is raised in the try block.
D:
It handles specific exceptions raised in the try block.
Answer: C

The else block in a try-except-else statement contains code that will be executed if no exception occurs in the try block.

Here's an example to illustrate:

try:
    # Code that might raise an exception
    result = 10 / 2
except ZeroDivisionError:
    # Handle specific exception types, if they occur
    print("Error: Division by zero!")
else:
    # Execute if no exception occurs in the try block
    print("No exception occurred.")
    print("Result:", result)

# Output:
# No exception occurred.
# Result: 5.0

In this example, if no exception is raised while performing the division operation in the try block, the else block will execute, printing "No exception occurred." and then printing the result of the division operation. If an exception occurs, the else block will be skipped, and the program will proceed to the except block.

Ad Slot (Above Pagination)
Quiz