Python Tutorial

# Python Logical Operators (and, or, not): Examples, Truth Table

• Introduction
• What are Logical Operators in Python?
• Types of Logical Operators in Python
• Truth Table of Logical Operators in Python
• Logical AND Operator in Python
• Logical OR Operator in Python
• Logical NOT Operator in Python
• Combining Logical Operators in Python
• Order of Evaluation of Python Logical Operators
• Short-Circuit Evaluation in Python
• Uses of Python Logical Operators
• Guidelines on Using Python Logical Operators Effectively

## Introduction

Decisions are at the heart of every operation in Python programming. To make these decisions, we rely on logical operators in Python, which act as the building blocks of conditional statements and play a crucial role in controlling the flow of our code.

Python logical operators allow developers to create sophisticated conditions and make their programs smarter and more efficient.

Whether you're new to Python or a seasoned developer, understanding how logical operators work and how to use them is essential. Hence, let’s learn these operators here in detail, with examples.

## What are Logical Operators in Python?

Logical operators in Python are symbols or words that allow you to perform logical comparisons or operations on Boolean values. These operators are used to determine the truth value of expressions, making them a fundamental part of decision-making and control flow in Python programs

Logical operators work with Boolean values (True or False) and return Boolean results.

They are commonly used in conditional statements (e.g., if, elif, and else) to control the flow of a program based on specified conditions.

## Types of Logical Operators in Python

There are three types of logical operators in Python- Logical AND, Logical OR, and Logical NOT operations.

### 1. AND (and):

The and operator returns True if both of its operands are True. It performs a logical AND operation. If either operand is False, the result is False.

### 2. OR (or):

The or operator returns True if at least one of its operands is True. It performs a logical OR operation. If both operands are False, the result is False.

### 3. NOT (not):

The not operator returns the opposite Boolean value of its operand. If the operand is True, not makes it False, and if the operand is False, not makes it True.

 OPERATOR DESCRIPTION SYNTAX AND Logical AND: Returns true if both the operands are true. x and y OR Logical OR: Returns true if either of the operands is true. x or y NOT Logical NOT: Returns true if an operand is false. not x

## Truth Table of Logical Operators in Python

Here's a truth table for all logical operators in Python, including and, or, and not. The table shows the result for all possible combinations of operands:

 Operand 1 Operand 2 and Result or Result not Result True True True True False True False False True False False True False True True False False False False True

This table shows the output of each logical operator when applied to Boolean operands. Remember that and returns True only if both operands are true, or returns True if at least one operand is true, and not negates the truth value of its operand.

## Logical AND Operator in Python

The and operator in Python is a logical operator that returns True if both of its operands are true; otherwise, it returns False.

It is used to combine multiple conditions, ensuring that all conditions must be true for the overall expression to be true.

For example:

``````x = True
y = False
result = x and y # result will be False because both x and y are not true``````

### Functionality and Working of AND Operator:

The and operator operates as follows:

• It takes two or more Boolean expressions as operands.

• It evaluates these expressions from left to right.

• If all the expressions are True, the and operator returns True.

• If any of the expressions is False, the and operator returns False.

• It uses short-circuit evaluation, which means that as soon as it encounters a False operand, it stops evaluating the remaining expressions, as they cannot change the outcome.

### Truth Table for AND Operator:

The truth table for the logical and operator in Python outlines all possible combinations of its operands and their corresponding results.

•
 Operand 1 Operand 2 Result True True True True False False False True False False False False

The result is True only when both operands are True.

### Examples of Logical AND Operator:

#### Example 1

``````age = 25
is_student = False
if age > 18 and not is_student:
print("You qualify for a discount.")``````

#### Example 2

``````username = "user123"
if len(username) > 5 and "@" in password:
print("Username is valid, and password contains '@'.")``````

In Example 1, the discount is granted only if the age is over 18 and the person is not a student.

In Example 2, the username must have more than 5 characters, and the password must contain the '@' symbol for the conditions to be true.

## Logical OR Operator in Python

The or operator in Python is a logical operator that returns True if at least one of its operands is true; it returns False only if both operands are false.

It is commonly used to create conditions where any one of the specified conditions must be true for the overall expression to be true.

### Functionality and How it Works:

The or operator operates as follows:

• It takes two or more Boolean expressions as operands.

• It evaluates these expressions from left to right.

• If at least one of the expressions is True, the or operator returns True.

• It returns False only if all the expressions are False.

• It uses short-circuit evaluation, which means that as soon as it encounters a True operand, it stops evaluating the remaining expressions because they cannot change the outcome.

#### For Example:

``````x = True
y = False
result = x or y  # result will be True because at least one of x and y is true``````

### Truth Table for Logical OR Operator:

The truth table for the or operator outlines all possible combinations of its operands and their corresponding results.

 Operand 1 Operand 2 Result True True True True False True False True True False False False

The result is False only when both operands are False.

### Examples of Logical OR Operator in Python:

#### Example 1

``````is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("You can sleep in today!")``````

#### Example 2

``````username = "admin"

In Example 1, the message is printed if it's either the weekend or a holiday.

In Example 2, the admin login is considered successful if either the username is "admin" or the password is "admin@123".

## Logical NOT Operator in Python

The not operator in Python is a logical operator that negates the truth value of its operand. If the operand is True, not will return False, and if the operand is False, not will return True.

It is often used to invert the logic of a condition or expression.

### Example:

``````x = True
result = not x  # result will be False because not True is False``````

### Examples of Logical NOT Operator in Python:

#### Example 1

``````is_raining = True
if not is_raining:
print("You can go for a walk.")``````

#### Example 2

``````is_logged_in = False
if not is_logged_in:

In Example 1, the message is printed only if it's not raining, demonstrating the inversion of the condition.

In Example 2, the message is printed if the user is not logged in, indicating that logging in is required to access the content.

### Combining NOT with Other Operators:

The not operator can be combined with other logical operators (and, or) to create more complex conditions.

``````is_weekend = True
is_holiday = False
if not (is_weekend or is_holiday):
print("It's a regular workday.")``````

Here, the message is printed if it's neither the weekend nor a holiday, showcasing the use of not in combination with or.

## Combining Logical Operators in Python

Combining Python logical operators allows you to create more complex conditions. The three main logical operators (and, or, and not) can be used together to express intricate conditions.

• ### Combining AND and OR Operators

You can use both and and or operators in a single expression for nuanced conditions.

``````age = 25
is_student = False
if age > 18 and not is_student:
print("You qualify for a discount.")``````

In this example, the condition is true if the age is over 18 and the person is not a student.

• ### Combining NOT with AND and OR Operators:

Using not along with and and or allows you to invert conditions as needed.

``````is_weekend = True
is_holiday = False
if not (is_weekend or is_holiday):
print("It's a regular workday.")``````

Here, the condition is true if it's neither the weekend nor a holiday, demonstrating the use of not in combination with or.

• ### Nested Logical Operators:

Nesting logical operators allows you to build even more complex conditions.

``````username = "admin"

In this example, the condition is true if the username is "admin" or "superadmin" and the password is at least 8 characters long.

## Order of Evaluation of Python Logical Operators

When there are multiple operators, Python evaluates the expression from left to right. There are three logical operators in Python, and we must evaluate an expression to evaluate these operators. The precedence of logical operators in Python is :

``   Not > And > Or``

Here are the details of the order of evaluation of logical operators in Python:

• Not logical operator is at the highest precedence.

• And operator is at the medium precedence.

• Or operator is at the lowest precedence.

Let’s understand it in detail:

### 1. NOT (not):

The not operator has the highest precedence. It is evaluated first in a logical expression.

#### Example:

``````result = not x and y
# Equivalent to: (not x) and y``````

### 2. AND (and):

The and operator is evaluated next. It has a lower precedence than not but higher than or.

#### Example:

``````result = x and y or z
# Equivalent to: (x and y) or z``````

### 3. OR (or):

The or operator has the lowest precedence among logical operators. It is evaluated last in a logical expression.

#### Example:

``````result = x or y and z
# Equivalent to: x or (y and z)``````

It's important to note that parentheses can be used to explicitly specify the order of evaluation and to override the default precedence. Using parentheses helps make complex expressions clearer and avoids ambiguity.

#### Example with Parentheses:

``result = (x or y) and not z``

In this example, the parentheses ensure that the or operation is performed before the and operation, and the not operation is applied to z.

## Short-Circuit Evaluation in Python

Short-circuit evaluation is a behavior in programming languages, including Python, where the second operand of a logical expression is not evaluated if the outcome can be determined by the first operand alone.

This optimization is particularly useful when dealing with logical operators (and and or) and can improve the efficiency of code execution.

### How Short-Circuit Evaluation Works:

For the and operator, if the first operand is False, the overall result will be False, and there's no need to evaluate the second operand since it cannot change the outcome.

For the or operator, if the first operand is True, the overall result will be True, and the second operand is not evaluated for the same reason.

### Examples of Short-Circuit Evaluation:

#### Example 1: Short-Circuit with AND Operator

``````x = False
y = True
result = x and (y / 0)  # Division by zero error won't occur due to short-circuit``````

In this example, the second operand (y / 0) is not evaluated because the first operand x is False. Therefore, no division by zero error occurs.

#### Example 2: Short-Circuit with OR Operator

``````a = True
b = (10 / 0)  # Division by zero error would occur
result = a or b  # Short-circuit prevents the division by zero error``````

Here, the second operand (10 / 0) is not evaluated because the first operand a is True. As a result, the division by zero error is avoided.

### Common Use Cases:

Short-circuit evaluation is often used when checking conditions that involve potential errors or resource-intensive operations.

It can be utilized to avoid unnecessary computations when the outcome is already determined.

### Example: Avoiding Division by Zero Error

``````divisor = 0
numerator = 10
if divisor != 0 and (numerator / divisor) > 5:
print("Result is greater than 5.")
else:
print("Error: Division by zero or result is not greater than 5.")``````

In this example, short-circuit evaluation prevents the division by zero error by checking divisor != 0 first.

## Uses of Python Logical Operators

Python logical operators have various practical uses in programming to make decisions, create conditional statements, and perform logical comparisons:

### 1. Conditional Statements (if, elif, else)

Logical operators are frequently used to create conditional statements that control the flow of a program. For example, you can use if with logical operators to execute a block of code if a certain condition is met. Additionally, elif and else can be used to handle multiple conditions.

``````if x > 10 and y < 5:
# Code to execute when both conditions are true
elif x < 0 or y > 20:
# Code to execute when at least one condition is true
else:
# Code to execute if no condition is true``````

### 2. Loop Control

Logical operators can be used in loops to control the iteration process. For instance, you can use them to create exit conditions in while loops or to determine when to continue or break out of a loop.

``````while condition1 and condition2:
# Continue looping as long as both conditions are true``````

### 3. Filtering and Data Selection

In data processing and analysis, logical operators are used to filter and select data that meets specific criteria. For instance, you can filter records in a database or select items from a list that satisfy certain conditions.

``filtered_data = [item for item in data if item > 10 and item % 2 == 0]``

### 4. Error Handling

Logical operators can help in error handling and exception management. They are used to create conditions for raising exceptions or handling different error scenarios.

``````try:
# Code that may raise an error
except Exception as e:
if condition:
# Handle the error in a specific way
else:
# Handle the error differently``````

### 5. Toggle States

Logical operators can be used to toggle states or boolean flags. For instance, you can use the not operator to change the state of a variable.

``````is_enabled = True
is_enabled = not is_enabled  # Toggle the state``````

### 6. Password Validation

Logical operators are often used to validate passwords or access control. For example, you can require that a user's password meets multiple criteria (e.g., length and complexity) using logical operators.

``is_valid_password = len(password) >= 8 and any(c.isupper() for c in password)``

### 7. Combining Multiple Conditions

Logical operators allow you to create complex conditions by combining multiple expressions. This is useful when you need to test multiple conditions simultaneously.

``````if condition1 and (condition2 or condition3) and not condition4:
# Execute code when a complex condition is met``````

## Guidelines on Using Python Logical Operators Effectively

Using logical operators in Python effectively and efficiently is crucial for writing clear, concise, and optimized code.

### 1. Understand Operator Precedence

Be aware of the precedence of logical operators in Python. The not has the highest precedence, followed by and, and then or. Use parentheses to clarify the order of evaluation when combining operators.

### 2. Keep Expressions Simple and Readable

Avoid overly complex logical expressions that can be difficult to understand. Break down complex conditions into smaller, more manageable parts with meaningful variable names.

### 3. Use Parentheses for Clarity

When combining different logical operators, use parentheses to explicitly define the order of evaluation. This improves code readability and reduces the likelihood of errors.

``````# Unclear
if x and y or not z:
# Better
if (x and y) or (not z):``````

### 4. Leverage Short-Circuit Evaluation

Take advantage of short-circuit evaluation to optimize your code. If the second operand in a logical expression does not need to be evaluated, short-circuiting can save unnecessary computations.

### 5. Consider the Context

Tailor your use of logical operators to the specific context of your code. For example, use and when both conditions are essential, and use or when either condition is sufficient.

### 6. Use De Morgan's Laws

De Morgan's Laws can be useful for simplifying complex logical expressions. The laws state that the negation of a conjunction (AND) is the disjunction (OR) of the negations, and the negation of a disjunction is the conjunction of the negations.

``````# Before applying De Morgan's Laws
if not (x and y):
# After applying De Morgan's Laws
if (not x) or (not y):``````

### 7. Avoid Unnecessary Negations

While negation (not) is a powerful tool, excessive use can make code harder to read. Whenever possible, express conditions directly without unnecessary negations.

``````# Unclear
if not (not x and y):
# Better
if x or not y:``````

### 8. Document Complex Conditions

If you have a complex logical condition, consider adding comments to explain the logic behind it. This helps other developers (and your future self) understand the reasoning behind the condition.

### 9. Test Thoroughly

Test your code with various inputs to ensure that your logical conditions behave as expected. Consider edge cases and different scenarios to cover a wide range of possible conditions.

### 10. Follow Coding Standards

If you're working in a team or following a specific coding style guide, adhere to the established conventions for the use of logical operators. Consistent coding practices make the codebase more maintainable.

Learn Next:-

More Tutorials:-

Compilers to Practice Online:-