7.5. Omitting the else Clause: Unary Selection¶
Another form of the if
statement is one in which the else
clause is omitted entirely. This creates what is sometimes called
unary selection. In this case, when the condition evaluates to
True
, the statements are executed. Otherwise the flow of
execution continues to the statement after the body of the if
.
1
x: int
2
x = 10
3
if x < 0:
4
print("The negative number " + str(x) + " is not valid here.")
5
print("This is always printed")
6
(ch05_unaryselection)
What would be printed if the value of x
is negative? Try it.
Check your understanding
select-5-1: What does the following code print?
x: int
x = -10
if x < 0:
print("The negative number " + str(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
select-5-2: Will the following code cause an error?
x: int
x = -10
if x < 0:
print("The negative number " + str(x) + " is not valid here.")
else:
print(str(x + " is a positive number")
else:
print("This is always printed")
You have attempted 1 of 4 activities on this page