Python’s && Equivalent: Logical And

In Python, the equivalent of && (logical-and) in programming languages such as C++ or Java in an if-statement is and. Using && will raise a SyntaxError, so use and instead!

Overview

Problem: What is the equivalent of &&(logical-and) in Python?

Example: Let’s have a look at the following example:

num_1 = [11, 21, 31, 41, 51]
num_2 = [15, 16, 17, 18, 19, 20, 21]
if len(num_1) % 2 == 0 && len(num_2) % 2 == 0:
    print("The lists has even number of elements")
elif len(num_1) % 2 != 0 && len(num_2) % 2 != 0:
    print("odd numbers")
else:
    print("mix of odd and even numbers")

Output: You will get the following error inside the “if” statement.

    if len(num_1) % 2 == 0 && len(num_2) % 2 == 0:
                            ^
SyntaxError: invalid syntax

Well! This can be really frustrating. You have got the logic right, yet there’s an error. Why? The answer is not as difficult as you might have thought.

We encountered the syntax error because of the usage of && operator in our code. Python does not have the provision for the && operator. Hence, when Python comes across “&&” in the program, it is unable to identify the operator and deems it as invalid. Therefore, we see the Syntax Error.Β 

πŸ‘‰ Instant Fix: Replace the && operator with and, which will solve the issue.

Logical Operators in Python

What are Operators in Python? Operators are the special symbols that are used to perform operations on the variables and values. They carry out arithmetic and logical computations.

The logical operators in Python are used on conditional statements, i.e, either True or False. The three logical operations are:

  • (i) Logical AND
  • (ii) Logical OR
  • (iii) Logical NOT.
OperatorDescriptionExample
andReturns True if both operands are True, and False otherwise.(True and True) == True
orReturns True if one operand is True, and otherwise it returns False.(False or True) == True
notReturns True if the single operand is False, otherwise returns False.(not True) == False

Logical AND

The Logical AND operator is used to return True if both operands are True. However, if any one of the two operands is False, then it returns False.Β 

Let’s look at an example to understand this:

# functioning of Logical and operator
val_1 = -5
val_2 = 10  
if val_1 > 0 and val_2 > 0:
    print("The numbers are positive numbers")
elif val_1 < 0 and val_2 < 0:
    print("The numbers are negative numbers")
else:
    print("One of the given numbers is positive while the other number is negative!")

Output:

One of the given numbers is positive while the other number is negative!

Now let’s get back to our first example. When we replace the && with and the error gets solved.

Solution:

val_1 = [11, 21, 31, 41, 51]
val_2 = [15, 16, 17, 18, 19, 20, 21]
# Using logical and
if len(val_1) % 2 == 0 and len(val_2) % 2 == 0:
    print("List has Even number of elements.")
elif len(val_1) % 2 != 0 and len(val_2) % 2 != 0:
    print("List has odd number of elements.")
else:
    print("List 1 has Odd number of elements while list 2 has even number of elements!")

Output:

List has odd number of elements.

Hence, and” is Python’s equivalent of && (logical-and) in an if-statement. In the same way, we cannot use the ||Β operator in Python as it is not valid. We have to use its equivalent logical or which is denoted by “or” in Python.

Logical OR

The Logical OR operator is used to return True if either of the operands is True. It returns false only if both of the operands are False

Let’s look at one example to understand this:

# functioning of Logical or operator
num_1 = -5
num_2 = -10  
num_3 = 8
print("For the first two numbers:")
if num_1 > 0 or num_2 > 0:
    print("Either of the numbers is positive")
else:
    print("Numbers are negative numbers")
print("For the last two numbers")
if num_2 > 0 or num_3 > 0:
    print("Either of the numbers is positive")
else:
    print("Numbers are negative numbers")

Output:

For the first two numbers:
Numbers are negative numbers
For the last two numbers
Either of the numbers is positive

The Python Advantage of Logical Operators

Python is a way more user-friendly language. While you have to use symbols like “&&” and “||” in some other languages like C++ and Java, Python makes life easy for you by providing direct words like “and” , “or“, etc which make more sense and resemble normal English.

Further, logical operators (in most languages) have the advantage of being short-circuited. This means that it first evaluates the first operand, and if only the first operand defines the result, then the second operand is not evaluated at all.

Look at the following example:

def check(v):
    print(v)
    return v
temp = check(False) and check(True)

# False

In the above example, only one print statement is executed, i.e., Python evaluated only the first operand. As we know the AND operator returns False, if one of the operands is False. The first operand, in this case, was False hence Python did not evaluate the second operand.Β Β 

However, let’s look at a different situation-

def check(v):
    print(v)
    return v


print("Output for first call: ")
temp = check(True) and check(True)
print("Output for the second call:")
temp = check(True) and check(False)

Output:

Output for first call: 
True
True
Output for the second call:
True
False

In the above example, as the first operand is True we cannot determine the result for the “and” operation. Hence, Python needs to evaluate the second operand as well. 

It works similarly for the OR operand where Python first checks the first operand.Β As we know, the OR logical operator returns False only if both of the operands are False. So, if the first operand is False only then it evaluates the second operand. However, if the first operand is True, it concludes that the output is True without even checking the second operand.

🎁Bonus: Pseudocode for AND and OR function is as follows:

def and(oper1, oper2):
    left = evaluate(oper1)
    if bool(left):
        return evaluate(oper2)
    else:
        return left
def or(oper1, oper2):
    left = evaluate(oper1)
    if bool(left):
        return left
    else:
        return evaluate(oper2)

Here are some questions and their quick solution, which are frequently asked along with the problem discussed in this article –

How to use “and” operator to check equality between strings?

Solution:

word = "MADAM"
if word and word[::-1]:
    print("PALINDROME!")

# PALINDROME

What is the replacement for the switch statement in Python?

Solution:

def switch(x):
    return {
        "1": 'One',
        "2": 'Two'
    }.get(x, "wrong entry!")


n = input("Enter your Choice: ")
print(switch(n))

Output:

Enter your Choice: 1
One

Conclusion

In this article, we learned about the logical operators and Python’s equivalent of && (logical-and) and || (logical-or) in an if-statement. I hope this article has helped you. Please stay tuned and subscribe for more such articles.

Recommended Read: Python And Operator