Bytes
Data SciencePython

Logical Operators in Python (With Examples)

Last Updated: 10th November, 2024
icon

Arunav Goswami

Data Science Consultant at almaBetter

Learn how to use logical operators in Python, including and, or, and not, with examples. Know more about their functions, precedence, and Pythonic applications

Python logical operators are essential for handling decision-making in programming. These operators evaluate expressions, returning a Boolean value (True or False) based on the logic defined. Python offers three main logical operators: andor, and not, which allow developers to create complex conditions for controlling the flow of code.

What are Logical Operators in Python

In Python, logical operators work with Boolean values and are used in expressions to perform logic-based evaluations. The output of logical operations determines whether certain code blocks execute. Logical operators are pivotal in scenarios such as:

  • Conditional statements (if, elif, else)
  • Loop controls (while and for loops)
  • Boolean algebra
  • Complex condition formulation

Logical operators follow Python’s syntactical conventions and apply rules for short-circuiting, which means evaluating only as far as necessary to determine an outcome.

Types of Logical Operators in Python

Python supports three primary logical operators:

  1. and
  2. or
  3. not

Each operator has distinct behavior in evaluating expressions.

1. The and Operator

The and operator returns True if both expressions are True; otherwise, it returns False. It follows a straightforward Boolean logic rule:

  • True and True returns True
  • True and False returns False
  • False and True returns False
  • False and False returns False

Usage of and

The and operator is commonly used in situations where multiple conditions must be met for code execution. For instance:

age25
income50000

if age > 18 and income > 30000:
    print("Eligible for loan")

Explanation: Here, the program checks if age is greater than 18 and income is greater than 30000. If both conditions hold, it prints "Eligible for loan."

2. The or Operator

The or operator evaluates to True if at least one of the expressions is True. The following logical rules apply:

  • True or True returns True
  • True or False returns True
  • False or True returns True
  • False or False returns False

Usage of or

The or operator is ideal when any one of multiple conditions should result in a True outcome:

age17
income35000

if age > 18 or income > 30000:
    print("Eligible for partial loan")

Explanation: Here, even though age is not greater than 18, the income meets the condition. Therefore, the program will output "Eligible for partial loan."

3. The not Operator

The not operator inverts the Boolean value of an expression. It changes True to False and vice versa:

  • not True returns False
  • not False returns True

Usage of not

The not operator is used when the requirement is to check for the negation of a condition:

is_studentFalse

if not is_student:
    print("Eligible for membership discount")

Explanation: Here, is_student is False, so not is_student returns True, and the program outputs "Eligible for membership discount."

Difference between the Logical Operators in Python

OperatorDescriptionExample ExpressionResultExplanation
andLogical ANDTrue and TrueTrueReturns True only if both expressions are True.
  True and FalseFalseIf any expression is False, the result is False.
orLogical ORTrue or FalseTrueReturns True if at least one expression is True.
  False or FalseFalseReturns False only if both expressions are False.
notLogical NOT (negation)not TrueFalseInverts the Boolean value; True becomes False, and False becomes True.
  not FalseTrueUseful for checking the opposite of a condition.

Logical Operators in Conditional Statements

Logical operators are frequently used within conditional statements to control program flow.

Example of Combining Logical Operators

In complex conditions, logical operators can be combined for multiple evaluations:

age20
is_employedTrue
has_bad_creditFalse

if age18 and is_employed and not has_bad_credit:
    print("Loan approved")

Explanation: Here, all three conditions must be met for "Loan approved" to be printed. If has_bad_credit were True, the not has_bad_credit would evaluate as False, causing the entire expression to return False.

Order of Evaluation (Precedence) in Logical Operators

Python has a specific order of evaluation for logical operators:

  1. not - highest precedence
  2. and
  3. or - lowest precedence

This order ensures that expressions are evaluated in a predictable manner. For instance:

resultTrue or False and not False
print(result)  # Outputs: True

Explanation:

  • not False evaluates to True
  • False and True evaluates to False
  • True or False finally evaluates to True

To alter the order of evaluation, parentheses can be used:

result = (True or Falseand not False
print(result)  # Outputs: True

Short-Circuit Evaluation in Logical Operators

Python uses short-circuit evaluation to optimize performance by stopping evaluation as soon as the result is determined:

  • For and: If the first condition is False, subsequent conditions are not evaluated.
  • For or: If the first condition is True, the rest are ignored.

Example of Short-Circuiting

def func1():
    print("Function 1 executed")
    return True

def func2():
    print("Function 2 executed")
    return False

print(func1() or func2())  # Only "Function 1 executed" is printed

Explanation: Since func1() returns True, func2() is not executed due to short-circuiting in the or operator.

Logical Operators in Python with Examples

Example 1: User Login Validation

username"admin"
password"12345"

if username == "admin" and password == "12345":
    print("Login successful")
else:
    print("Invalid credentials")

This example uses the and operator to check that both the username and password match expected values.

Example 2: Eligibility Check for Discount

age16
is_studentTrue

if age18 or is_student:
    print("Eligible for discount")

Here, the or operator checks if the user qualifies for a discount by either being under 18 or a student.

Example 3: Negating a Condition

is_registeredFalse

if not is_registered:
    print("User needs to register")

In this example, the not operator is used to ensure that unregistered users are prompted to register.

Common Pitfalls in Using Logical Operator in Python

  1. Neglecting Operator Precedence: Misunderstanding precedence can lead to unexpected results. Use parentheses to clarify operations.
  2. Improper Use of Short-Circuiting: Expecting all conditions to evaluate when using and or or can result in unexecuted code segments.
  3. Avoiding Complex Conditions: Too many logical conditions can reduce code readability. Break down complex conditions into smaller parts or use functions for clarity.

Logical Operators in Pythonic Code

Logical operators Python are key to writing efficient and Pythonic code. By leveraging logical operators, Python developers can create concise, expressive code for various applications, such as filtering data, validating input, and handling exceptions.

Example of Pythonic Use of Logical Operators

# Verifying both variables have values
value1, value2 = 1020

if value1 and value2:
    print("Both values are non-zero")

This code takes advantage of Python's truthy values, where non-zero numbers evaluate as True, simplifying the condition check.

Want to dive deeper into Python? Check out our comprehensive Python Cheat Sheet, experiment in our Online Python Compiler, or explore our complete Python Tutorial!

Conclusion

Logical operators in Python and, or, and not are fundamental in programming for controlling the flow of execution. These operators help developers build conditional logic, control loops, and write expressive code. Mastering logical operators is essential for writing clean, efficient, and optimized Python programs that can handle a variety of logic-based scenarios.

Ready to take your skills further? Enroll in our Data Science Course or pursue a Masters in Data Science to advance your career!

Related Articles

Top Tutorials

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter