Python Programming - Conditional Statements

Exercise : Conditional Statements - General Questions
  • Conditional Statements - General Questions
21.
What will be the output of the following code?
number = 15
result = "Even" if number % 2 == 0 else "Odd"
print(result)
Even
Odd
Error
No output
Answer: Option
Explanation:
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."

22.
How can you iterate over both the index and the elements of a list in a for loop?
Using for i in range(len(my_list))
Using for element in my_list
Using for i, element in enumerate(my_list)
Using for i, element in range(len(my_list))
Answer: Option
Explanation:
The enumerate() function is used to iterate over both the index and the elements of a list in a for loop.

23.
Which of the following is the correct syntax for a while loop?
while condition:
    # code block
while (condition)
    # code block
do while condition:
    # code block
for condition in while:
    # code block
Answer: Option
Explanation:
The correct syntax for a while loop in Python is to use the while keyword followed by a condition.

24.
What does the else block in a try-except-else statement execute?
It always executes, regardless of whether an exception occurs or not.
It executes only if an exception is raised in the try block.
It executes only if no exception is raised in the try block.
It handles specific exceptions raised in the try block.
Answer: Option
Explanation:

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.


25.
What is the purpose of the is keyword?
Checks for equality
Checks for inequality
Tests object identity
Performs mathematical operations
Answer: Option
Explanation:
The is keyword in Python is used to test if two variables refer to the same object in memory, checking object identity.