Logical Operators in Python with Examples|

Logical operators in Python are the building blocks of decision-making and conditional statements. They allow us to evaluate the truth or falsehood of conditions and control the flow of our programs accordingly. In this article, we will delve into the world of logical operators in python with example, understanding their importance, and exploring the three types of logical operators in Python with examples, so keep reading the article till last.

What are Logical Operators in Python ?

Logical operators are used to combine or manipulate boolean values (True or False). They enable us to create complex conditions by joining multiple boolean expressions. Python supports three primary logical operators: and, or, and not.

Different Types of Logical Operators in Python

  • logical and
  • logical or
  • logical not

Logical “and” Operator in Python

The logical AND operator (and) in Python is used to combine two boolean expressions and determine whether both expressions are True. If both expressions are indeed True, the result of the and operation is True; otherwise, it is False.

This operator is a fundamental tool for creating complex conditions that require multiple criteria to be satisfied. Let’s explore the logical AND operator in detail with simple examples.

Syntax:

expression1 and expression2

Working Principle:

The logical AND operator evaluates the first expression. If the first expression is True, it then evaluates the second expression. If both expressions are True, the overall result is True. If either of the expressions (or both) is False, the result is False.

Examples:

  1. Both Expressions are True:
x = True
y = True
result = x and y
print(result)             # Output: True

One Expression is False:

p = True
q = False
result = p and q
print(result)            # Output: False

Both Expressions are False:

a = False
b = False
result = a and b
print(result)            # Output: False

Use Cases :

  1. Conditional Statements
age = 25
has_id = True

if age >= 18 and has_id:
    print("You can enter the club.")
else:
    print("Entry denied.")

Explanation:

  1. in the above code, we have “age” variable with value “25”.
  2. We also defined a variable has_id with a value of True, denoting that person has identification.
  3. In the if statement, we used the logical AND operator (and) to check two conditions:
    • The first condition age >= 18 will be satisfied if the person is 18 years or older.
    • The second condition has_id will be satisfied if the person has identification.
  4. If both conditions are true, the message “You can enter the club.” will be printed.
  5. If either of the conditions is false, the message “Entry denied.” will be printed.

2. Validation

username = "admin"
password = "secret"

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

Explanation:

  1. We have a default username “admin” and password “secret” which represents valid login credentials.
  2. In the if statement, we use the logical AND operator to check two conditions:
    • The first condition username == "admin" checks if the provided username matches the valid username.
    • The second condition password == "secret" checks if the provided password matches the valid password.
  3. If both conditions are true, the message “Login successful.” is printed.
  4. If either of the conditions is false, the message “Invalid credentials.” is printed.

Logical “or” Operator in Python

Syntax :

expression1 or expression2

Working Principle:

The logical OR operator evaluates the first expression. If the first expression is True, then the result will be True . If the one expression is False, the operator then evaluates the second expression. If both expressions are False, the overall result will be False.

Examples:

  1. Both Expressions are True:
x = True
y = True
result = x or y
print(result)  # Output: True

One Expression is True:

p = True
q = False
result = p or q
print(result)  # Output: True

Both Expressions are False:

a = False
b = False
result = a or b
print(result)  # Output: False

Example 1: Using Logical OR in Conditional Statements

has_permission = True
is_admin = False

if has_permission or is_admin:
    print("Access granted.")
else:
    print("Access denied.")

Explanation:

  1. We have two boolean variables, has_permission and is_admin, indicating whether the user has permission and whether they are an admin.
  2. In the if statement, we use the logical OR operator (or) to check two conditions:
    • The first condition has_permission checks if the user has permission.
    • The second condition is_admin checks if the user is an admin.
  3. If either condition is True, then message “Access granted.” will be printed.
  4. If both conditions are False, then message “Access denied.” will be printed.

Example 2: Using Logical OR to Combine Conditions

weather = "rainy"
is_weekend = False

if weather == "rainy" or is_weekend:
    print("Stay indoors and relax.")
else:
    print("Enjoy your day!")

Explanation:

  1. We have variables weather and is_weekend representing the current weather condition and whether it’s the weekend.
  2. In the if statement, we use the logical OR operator to check two conditions:
    • The first condition weather == "rainy" checks if the weather is rainy.
    • The second condition is_weekend checks if it’s the weekend.
  3. If either condition is True, the message “Stay indoors and relax.” is printed.
  4. If both conditions are False, the message “Enjoy your day!” is printed.

These examples showcase how the logical OR operator allows you to create conditions based on multiple criteria where only one condition needs to be satisfied for a certain outcome. By using the logical OR operator effectively, you can build dynamic and versatile logic in your Python programs.

Logical “not” Operator in Python

The logical NOT operator (not) in Python is a unary operator that is used to negate the value of a boolean expression. It essentially returns the opposite boolean value of the operand. If the operand is True, applying the not operator makes it False, and vice versa. Let’s discuss the details of the logical NOT operator with straightforward examples.

Syntax:

not expression

Working Principle:

The logical NOT operator reverses the truth value of the expression it operates on. If the expression is True, the not operator returns False. If the expression is False, the not operator returns True.

Examples:

  1. Expression is True:
x = True
result = not x
print(result)  # Output: False

Expression is False:

y = False
result = not y
print(result)  # Output: True

Use Case 1: Using not in Conditional Statements

has_permission = False

if not has_permission:
    print("Access denied.")

Explanation:

  1. We have a variable has_permission initialized with the boolean value False, indicating that the user does not have permission.
  2. In the if statement, we use the not operator to negate the boolean value of has_permission.
  3. Since not False evaluates to True, the condition becomes True, and the message “Access denied.” is printed.

Use Case 2: Using not in Complex Conditions

temperature = 28
humidity = 80

if not (temperature > 25 and humidity < 90):
    print("Weather is not comfortable.")

Explanation:

  1. We have two variables, temperature set to 28 and humidity set to 80, representing weather conditions.
  2. In the if statement, we use the not operator to negate the entire logical expression enclosed in parentheses.
  3. The expression (temperature > 25 and humidity < 90) evaluates to True, as both conditions are met.
  4. Applying not to the True result makes it False.
  5. Therefore, the condition becomes False, and the message “Weather is not comfortable.” is printed.

Use Case 3: Using not in Conditional Loops

user_input = input("Enter 'exit' to quit: ")

while not (user_input == "exit"):
    user_input = input("Enter 'exit' to quit: ")

Explanation:

  1. We use a while loop to continually ask the user for input.
  2. The loop continues as long as the negated condition not (user_input == "exit") is True.
  3. If the user enters anything other than “exit”, the negated condition becomes True, and the loop continues.
  4. When the user enters “exit”, the condition becomes False, causing the loop to exit.

In all these use cases, the not operator allows us to invert the boolean value of a condition. It provides a way to express negation or the absence of a certain condition, making our code more expressive and flexible.

Conclusion

I hope you have understood about Logical Operators in python with example, what is logical operators in python, types of logical operators in python, what are logical operators in python etc. keep exploring…..

Hello Guys, Ayush this side. I am founder of studypunchx. I love to share trending and useful informations. keep Growing.....

Leave a Comment