0%

Making Decisions · practice

Reverse a Boolean with not

The and and or combine values. Python has one more Boolean operator, and it has one tidy job: not reverses a Boolean .

Reverse a Boolean with not

Run this example:

Try it

Because is_closed is False, not is_closed produces True.

Starting valueResult with not
TrueFalse
FalseTrue

That is the complete rule. not does not change the original ; it produces the opposite Boolean value.

Read not as part of the question

not is especially readable with a well-named Boolean variable:

Try it

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:

Try it

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:

Try it

Both produce 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 for needs_booking with an that uses 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 value while has_booking stays unchanged.