4.4. Alternative execution¶
A second form of the if
statement is alternative
execution, in which there are two possibilities and the
condition determines which one gets executed. The syntax looks like
this:
If the remainder when x
is divided by 2 is 0, then we know
that x
is even, and the program displays a message to that
effect. If the condition is false, the second set of statements is
executed.
Since the condition must either be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.
- TRUE
- TRUE is printed by the if-block, which only executes if the conditional (in this case, 4+5 == 10) is true. In this case 5+4 is not equal to 10.
- FALSE
- Since 4+5==10 evaluates to False, Python will skip over the if block and execute the statement in the else block.
- TRUE on one line and FALSE on the next
- Python would never print both TRUE and FALSE because it will only execute one of the if-block or the else-block, but not both.
- Nothing will be printed
- Python will always execute either the if-block (if the condition is true) or the else-block (if the condition is false). It would never skip over both blocks.
Q-2: What does the following code print?
if 4 + 5 == 10:
print("TRUE")
else:
print("FALSE")
- Output a
- Because -10 is less than 0, Python will execute the body of the if-statement here.
- Output b
- Python executes the body of the if-block as well as the statement that follows the if-block.
- Output c
- Python will also execute the statement that follows the if-block (because it is not enclosed in an else-block, but rather just a normal statement).
- It will cause an error because every if must have an else clause.
- It is valid to have an if-block without a corresponding else-block (though you cannot have an else-block without a corresponding if-block).
Q-3: What does the following code print?
x = -10
if x < 0:
print("The negative number ", x, " is not valid here.")
print("This is always printed")
a.
This is always printed
b.
The negative number -10 is not valid here
This is always printed
c.
The negative number -10 is not valid here
- No
- Every else-block must have exactly one corresponding if-block. If you want to chain if-else statements together, you must use the else if construct, described in the chained conditionals section.
- Yes
- This will cause an error because the second else-block is not attached to a corresponding if-block.
Q-4: Will the following code cause an error?
x = -10
if x < 0:
print("The negative number ", x, " is not valid here.")
else:
print(x, " is a positive number")
else:
print("This is always printed")
The following program should print out “x is even” if the remainder of x divided by 2 is 0 and “x is odd” otherwise, but the code is mixed up. Be sure to indent correctly!