Making Decisions · practice
Reverse a Boolean with not
The and and or combine not reverses a Boolean
Reverse a Boolean with not
Run this example:
Because is_closed is False, not is_closed produces True.
| Starting value | Result with not |
|---|---|
True | False |
False | True |
That is the complete rule. not does not change the original
Read not as part of the question
not is especially readable with a well-named Boolean variable:
Read if not is_raining: as “if it is not raining.” The code sounds like the question the program needs to ask, which is usually a good sign.
You can also store the reversed value for later:
The answer is True: without a booking, this visitor needs one.
Prefer a direct comparison when it reads better
not can reverse a comparison, but that does not always make the clearest sentence:
Both True. The direct comparison age >= 18 is easier to understand at a glance.
Use not when reversing a named Boolean idea sounds natural, such as not is_closed or not has_permission. Prefer the opposite comparison when it states the rule more directly.
Which condition is the clearest way to run a block when account_locked is false?
What does this code print?
has_ticket = True
needs_ticket = not has_ticket
print(needs_ticket)Reverse one useful fact
The exercise starts with has_booking set to False. Use not to store the opposite value in needs_booking, then check the two printed Boolean values. One small operator, one clear job.
Task
Replace the placeholder needs_booking with an not to reverse has_booking.
Keep has_booking and the two supplied print calls unchanged. The program should print False followed by True.
Once it works, press Step in the exercise editor and watch needs_booking receive the opposite has_booking stays unchanged.