Note 4.3.1.
This form of
if
statement is much less common than the if
-else
statement you learned about in Section 4.2.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
. Here is what the flowchart looks like:x
is negative? Try it.if
statement is much less common than the if
-else
statement you learned about in Section 4.2.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
if
statement here.if
block as well as the statement that follows the if
block.if
block because it is not enclosed in an else
block, but rather just a normal statement.if
must have an else
clause.if
block without a corresponding else
block (though you cannot have an else
block without a corresponding if
block).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")
if
block must have exactly one corresponding else
block. You will see how to make a chain of conditions in a later section.else
block is not attached to a corresponding if
block.if
and are of the opinion that every if
should always have an else
, Python has you covered with a special statement called pass
, which means “do nothing”.number = int(input("Enter a non-negative number: "))
if number < 0:
print("Sorry, negative numbers are not allowed.")
print("Your number was", number)
pass
so that we can have an else
clause to go with the if
:number = int(input("Enter a non-negative number: "))
if number < 0:
print("Sorry, negative numbers are not allowed.")
else:
pass
print("Your number was", number)