KAHIBARO Bookshelves
Discord Login Register

6.2. Logical operators

Logical operators

Logical operators let you combine and invert conditions. They are used inside if, elif, and while statements to build more complex decisions.

Python has three main logical operators:

  • and
  • or
  • not

They work with expressions that are either True or False (Boolean values).

`and`: all conditions must be True

and combines two (or more) conditions and is True only if all parts are True.

General idea:

$$
A \text{ and } B \text{ is True only if both } A \text{ and } B \text{ are True.}
$$

In Python:

age = 20
has_ticket = True
if age >= 18 and has_ticket:
    print("You can enter.")
else:
    print("You cannot enter.")

Here:

  • age >= 18 is True
  • has_ticket is True
  • True and True is True, so "You can enter." is printed.

Truth table for and:

  • True and True → True
  • True and False → False
  • False and True → False
  • False and False → False

`or`: at least one condition must be True

or combines conditions and is True if at least one part is True.

General idea:

$$
A \text{ or } B \text{ is False only if both } A \text{ and } B \text{ are False.}
$$

Example:

is_admin = False
is_moderator = True
if is_admin or is_moderator:
    print("You have special access.")
else:
    print("Normal user access.")

Here:

  • is_admin is False
  • is_moderator is True
  • False or True is True, so "You have special access." is printed.

Truth table for or:

  • True or True → True
  • True or False → True
  • False or True → True
  • False or False → False

`not`: reverse a condition

not flips True to False and False to True.

General idea:

$$
\text{not } A \text{ is True if and only if } A \text{ is False.}
$$

Example:

logged_in = False
if not logged_in:
    print("Please log in first.")
  • logged_in is False
  • not logged_in is True
  • The message is printed.

Truth table for not:

  • not True → False
  • not False → True

Combining multiple logical operators

You can use and, or, and not together to build more detailed conditions.

Example:

age = 16
has_permission = True
if (age >= 18 or has_permission) and not (age < 10):
    print("Allowed.")
else:
    print("Not allowed.")

Read step by step:

  1. age >= 18 → False
  2. has_permission → True
  3. age >= 18 or has_permission → False or True → True
  4. age < 10 → False
  5. not (age < 10) → not False → True
  6. Final: True and True → True → "Allowed."

Operator precedence and parentheses

When you combine multiple logical operators, Python does not always evaluate them from left to right. There is an order (precedence):

  1. not
  2. and
  3. or

For example:

result = True or False and False
print(result)

This is evaluated as:

  • False and False → False
  • True or False → True

So result is True.

If you want a different order, use parentheses:

result = (True or False) and False
print(result)  # This is False

Parentheses make your code clearer and safer, especially for beginners.

Common patterns with logical operators

Checking a range with `and`

A common use is to check that a value is between two numbers:

temperature = 22
if temperature >= 18 and temperature <= 25:
    print("Comfortable temperature.")

Python also allows this shorter form (just to recognize it when you see it):

if 18 <= temperature <= 25:
    print("Comfortable temperature.")

Multiple allowed values with `or`

Use or when any of several values is acceptable:

day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")

Typical beginner mistakes with logical operators

1. Using `and` instead of `or` (and vice versa)

Example:

color = "red"
# Wrong if you mean "red OR blue"
if color == "red" and color == "blue":
    print("Primary color.")

This condition is always False because color cannot be both "red" and "blue" at the same time.

Correct:

if color == "red" or color == "blue":
    print("Primary color.")

2. Forgetting to repeat the variable in comparisons

Incorrect:

age = 20
# This does NOT do what it seems
if age == 18 or 20:
    print("Age is 18 or 20")

age == 18 or 20 is interpreted as (age == 18) or 20, and 20 is always treated as True in this context, so the condition always passes.

Correct:

if age == 18 or age == 20:
    print("Age is 18 or 20")

3. Relying on precedence instead of using parentheses

This can make code confusing and lead to bugs:

age = 17
has_permission = True
with_parent = True
# Harder to read and can be misinterpreted
if age >= 18 or has_permission and with_parent:
    print("You can enter.")

Better with parentheses to show the intended logic:

if age >= 18 or (has_permission and with_parent):
    print("You can enter.")

Practice ideas

Try writing small if statements using logical operators:

  • Ask the user for their age and day of the week, and allow a discount if:
    • they are under 18 or
    • it is Wednesday.
  • Ask for a score, and print "Pass" only if it is at least 50 and not greater than 100.
  • Ask if it is raining and if the user has an umbrella; print whether they can go outside based on combinations of and, or, and not.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms