Python’s if...else
statement is a fundamental control flow tool that allows you to execute code based on certain conditions. Here we present 12 multiple-choice questions to test your knowledge of Python if-else statement. Each MCQ has the correct answer with an explanation.
1. What is the correct syntax for an if statement in Python?
Answer:
Explanation:
In Python, the syntax for an if statement is 'if' followed by the condition, a colon, and then the block of code to execute if the condition is true.
2. How do you check for multiple conditions in a single if statement?
Answer:
Explanation:
Python uses 'and' to check if multiple conditions are true.
3. How would you write an if statement that executes when x is not equal to 10?
Answer:
Explanation:
The '!=' operator is used in Python to check if two values are not equal.
4. Which keyword is used for executing a block of code if the if condition is false?
Answer:
Explanation:
The 'else' keyword is used in Python to execute a block of code when the if condition is false.
5. How do you implement multiple conditions that trigger different blocks of code?
Answer:
Explanation:
Python uses 'elif', short for 'else if', for multiple, mutually exclusive conditions in an if statement.
6. What is the output of the following code?
x = 10
if x > 10:
print("Greater")
elif x == 10:
print("Equal")
else:
print("Lesser")
Answer:
Explanation:
The code checks if x is greater than, equal to, or less than 10. Since x is 10, it prints "Equal".
7. How do you write a one-line if statement in Python?
Answer:
Explanation:
Python allows one-line if statements, where the action is before the condition, separated by 'if'.
8. What is the correct way to check if a list is empty in an if statement?
Answer:
Explanation:
All three methods are correct for checking if a list is empty in Python.
9. Can an if statement contain only an else clause without elif?
Answer:
Explanation:
An if statement can have an else clause without an elif, as elif is optional.
10. What is the result of the following code?
x = 5 if x > 10: print("A") else: if x > 7: print("B") else: print("C")
Answer:
Explanation:
The code uses nested if statements. Since x is 5, which is not greater than 10 or 7, it prints "C".
11. Which keyword allows you to check if a condition is false in an if statement?
Answer:
Explanation:
The 'not' keyword is used to check if a condition is false in Python.
12. How do you check for the existence of a key in a dictionary within an if statement?
Answer:
Explanation:
The syntax 'if key in dictionary:' is used to check if a key exists in a dictionary.