Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

🧠 Python Logical Operators: Complete Guide

Python Logical Operators - Complete Guide

Logical operators are the building blocks of decision-making in Python programs.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What are Logical Operators?
  • AND Operator (and)
  • OR Operator (or)
  • NOT Operator (not)
  • Truth Tables
  • Operator Precedence
  • Real-World Examples
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What logical operators are — tools to combine boolean conditions
  • AND Operator (and) — True only if both conditions are True
  • OR Operator (or) — True if at least one condition is True
  • NOT Operator (not) — reverses the boolean value
  • Truth Tables — visualize logical operator behavior
  • Operator Precedence — order of evaluation
  • Real-world examples — user authentication, eligibility checks
  • Common mistakes — and how to avoid them

What are Logical Operators?

Logical operators are used to combine conditional statements. They work with boolean values (True and False) and return a boolean result. Python provides three logical operators: and, or, and not.

šŸ’” Key insight: Logical operators are like the "glue" that connects multiple conditions together. They let you create complex decision-making logic with simple, readable code.

Think of logical operators as question combiners. Instead of asking one question at a time, you can combine multiple questions: "Is the user logged in AND has permission?" or "Is the user an admin OR a moderator?"

1. AND Operator (and)

The AND operator (and) returns True only if both conditions are True. If any condition is False, the result is False.

# AND Operator Examples
print(True and True)    # Output: True
print(True and False)   # Output: False
print(False and True)   # Output: False
print(False and False)  # Output: False

# With variables
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive)        # Output: True

# Short-circuit evaluation
x = 5
print(x > 0 and x < 10)  # Output: True

2. OR Operator (or)

The OR operator (or) returns True if at least one condition is True. It only returns False when both conditions are False.

# OR Operator Examples
print(True or True)     # Output: True
print(True or False)    # Output: True
print(False or True)    # Output: True
print(False or False)   # Output: False

# With variables
has_cash = False
has_card = True
can_pay = has_cash or has_card
print(can_pay)          # Output: True

# Short-circuit evaluation
x = 5
print(x < 0 or x > 0)   # Output: True

3. NOT Operator (not)

The NOT operator (not) reverses the boolean value. It returns True if the condition is False, and False if the condition is True.

# NOT Operator Examples
print(not True)         # Output: False
print(not False)        # Output: True

# With variables
is_weekend = False
is_workday = not is_weekend
print(is_workday)       # Output: True

# Combining with other operators
age = 15
can_vote = age >= 18
cannot_vote = not can_vote
print(cannot_vote)      # Output: True

4. Truth Tables

Truth tables help visualize how logical operators work. Here are the truth tables for AND, OR, and NOT:

AND (and)

Condition 1 Condition 2 Result
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

OR (or)

Condition 1 Condition 2 Result
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

NOT (not)

Condition Result
TrueFalse
FalseTrue

5. Operator Precedence

When combining multiple logical operators, Python follows a specific order of evaluation:

Precedence (highest to lowest):

1. not        (highest)
2. and
3. or         (lowest)

# Examples
result = True or False and False
# and is evaluated first: False and False = False
# then or: True or False = True
print(result)  # Output: True

# Use parentheses for clarity
result = (True or False) and False
print(result)  # Output: False

6. Real-World Examples

šŸ” User Authentication

# User Authentication Example
is_logged_in = True
has_permission = True
is_admin = False

# Check if user can access dashboard
can_access = is_logged_in and (has_permission or is_admin)
print(f"Can access dashboard: {can_access}")  # Output: True

šŸ“Š Grade Eligibility Check

# Grade Eligibility Example
score = 85
attendance = 90
has_passed = score >= 75 and attendance >= 80
print(f"Student passed: {has_passed}")  # Output: True

šŸ›’ Discount Eligibility

# Discount Eligibility Example
total = 150
is_member = True
has_coupon = False

# Get discount if total > 100 AND (is_member OR has_coupon)
eligible = total > 100 and (is_member or has_coupon)
print(f"Eligible for discount: {eligible}")  # Output: True

7. Common Mistakes to Avoid

āŒ Mistake 1: Using & instead of and

& is a bitwise operator, not a logical operator. Always use and, or, not for boolean logic.

# WRONG
if x > 0 & x < 10:  # & is bitwise AND, not logical AND

# CORRECT
if x > 0 and x < 10:  # Use 'and' for logical AND

āŒ Mistake 2: Misunderstanding operator precedence

not has higher precedence than and, which has higher precedence than or. Use parentheses to avoid confusion.

# WRONG (unclear precedence)
if not x > 5 or y < 10:
    pass

# CORRECT (using parentheses)
if not (x > 5 or y < 10):
    pass

āŒ Mistake 3: Comparing with non-boolean values

Python treats certain values as False (0, None, empty strings, empty lists). Be careful when using them with logical operators.

# Truthy and Falsy values
print(0 and 5)     # Output: 0 (first Falsy value)
print(5 and 0)     # Output: 0 (second Falsy value)
print(5 and 10)    # Output: 10 (last value)

# Always use explicit comparisons for clarity
if x is not None and x > 0:
    pass

Try It Yourself!

Experiment with logical operators directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
LOGICAL OPERATORS
========================================

1. AND OPERATOR (and)
True and True: True
True and False: False
False and False: False

2. OR OPERATOR (or)
True or True: True
True or False: True
False or False: False

3. NOT OPERATOR (not)
not True: False
not False: True

4. REAL-WORLD EXAMPLE (Authentication)
Can access dashboard: True

āœ… Logical operators are essential for decision-making!
šŸ†

šŸŽ‰ You've Mastered Python Logical Operators!

You understand AND, OR, NOT operators, truth tables, and operator precedence. These are essential for building decision-making logic in Python!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about Python logical operators:

1. What is the result of True and False?
2. What does the or operator return when one condition is True and one is False?
3. What is the result of not False?
4. What is the correct precedence order of logical operators from highest to lowest?
5. What is the result of True or False and False?

Frequently Asked Questions

šŸ¤” What's the difference between and and &? ā–¼

and is a logical operator used for boolean logic. & is a bitwise operator used for bit-level operations. Always use and for conditions like if x > 0 and x < 10.

šŸ”§ What is short-circuit evaluation? ā–¼

Short-circuit evaluation means Python stops evaluating as soon as the result is known. For and, if the first condition is False, the second isn't evaluated. For or, if the first condition is True, the second isn't evaluated.

šŸ“ What are truthy and falsy values in Python? ā–¼

Falsy values are treated as False in boolean contexts: None, 0, empty strings (""), empty lists ([]), empty dictionaries ({}). Everything else is truthy (True).

šŸ“Š Can I use logical operators with non-boolean values? ā–¼

Yes! and returns the first falsy value or the last truthy value. or returns the first truthy value or the last falsy value. not always returns a boolean.

⚔ What is the difference between or and |? ā–¼

or is a logical operator for boolean logic. | is a bitwise OR operator for bit-level operations. Use or for conditions and | for bit manipulation.

šŸŽÆ How do I combine multiple logical operators? ā–¼

Use parentheses to make your logic clear and avoid precedence confusion. For example: if (age >= 18 and has_license) or is_admin: is much clearer than if age >= 18 and has_license or is_admin.

šŸ“š Where to Go From Here

Now that you understand Python logical operators, here are some related topics to explore:

šŸ“Š Relational Operators

Compare values with >, <, ==, !=

šŸŽÆ Decision Making

Use conditions to control program flow

šŸ“ If Statements

Make decisions with if, elif, else

šŸ“– Related Tutorials
  • Relational Operators
  • Decision Making
  • if Statements
  • Arithmetic Operators
šŸ“– Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Relational Operators Next: Bitwise Operators →