Python Foundations · Lesson 5 of 12

Boolean logic

Combining conditions with and, or and not. Learn through short examples, practical tasks and targeted questions.

← All lessons

Combining Boolean conditions

The operators and, or and not combine or reverse conditions. They are useful for age checks, passwords and deciding whether several requirements have been met. Create a truth table to predict the result before running the code.

Watch out: With and, both conditions must be true; with or, at least one must be true. Be careful when using not with compound expressions.

1 · Understand

Combining conditions with and, or and not. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

age = 16
has_pass = True
if age >= 16 and has_pass:
    print("Entry allowed")
Download example .py ↓

2 · Practise

Require a password of at least eight characters and a username that is not empty.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
username = input("Username: ")
password = input("Password: ")
if username != "" and len(password) >= 8:
    print("Accepted")
else:
    print("Try again")
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

age = 13
if age >= 12 or <= 18:
    print("Teen")
Reveal the corrected program and explanation
age = 13
if age >= 12 and age <= 18:
    print("Teen")

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

When is A and B true?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →