Exercise: Python

Questions for: Conditional Statements

In Python, how can you represent the logical NOT operator in an if statement?
A:
!=
B:
not
C:
<>
D:
nor
Answer: B

The not keyword is used as the logical NOT operator in Python. It is used to negate the truth value of a condition.

The != operator in Python is used for inequality comparison, not for logical negation. It checks if two values are not equal to each other. It's not used directly to represent logical NOT in an if statement.

What will be the output of the following code?
num = 0
if num > 0:
    print("Positive")
elif num < 0:
    print("Negative")
else:
    print("Zero")
A:
Positive
B:
Negative
C:
Zero
D:
No output
Answer: C
The code checks if num is greater than 0, less than 0, or equal to 0. Since num is 0, the code inside the else block will be executed, printing "Zero."
Which logical operator is used to combine multiple conditions in an if statement?
A:
&&
B:
||
C:
and
D:
in
Answer: C
The and keyword is used as the logical AND operator to combine multiple conditions in an if statement. Both conditions must be true for the combined condition to be true.
What will happen if the following code is executed?
temperature = 25
if temperature > 30:
    print("It's hot!")
elif temperature > 20:
    print("It's warm.")
else:
    print("It's cool.")
A:
It will print "It's hot!"
B:
It will print "It's warm."
C:
It will print "It's cool."
D:
It will print nothing (no output)
Answer: B
The code checks multiple conditions using if and elif. Since temperature is 25, it satisfies the second condition (temperature > 20), and the corresponding code block inside the elif will be executed, printing "It's warm."
Which of the following is the correct syntax for an if statement with multiple conditions?
A:
if condition1:
    # code block
if condition2:
    # code block
B:
if condition1:
    # code block
elif condition2:
    # code block
C:
if condition1:
    # code block
else if condition2:
    # code block
D:
if condition1:
    # code block
else condition2:
    # code block
Answer: B

The correct syntax for an if statement with multiple conditions is to use elif (short for "else if") for subsequent conditions after the initial if statement.

Option A is also a valid syntax for handling multiple conditions, but it doesn't ensure mutual exclusivity between the conditions. In this case, both code blocks would execute if both condition1 and condition2 are true.

Ad Slot (Above Pagination)
Quiz