Logical Operators in Python

In programming, you will often come across situations where you will need to evaluate multiple conditions. For example, you may want to perform an action when the price of a stock is above 10 but below 12. Logical operators come into play in such situations. These logical operators allow a program to make a decision based on multiple conditions.

There are three logical operators: and, or and not.

and (&)

This is called the logical 'and' operator. The logical 'and' operator (&) returns the boolean value true if both operands are true and returns false otherwise. The following examples illustrate this:

#Assign values to Stock A and Stock B
stock_A = 10
stock_B = 12
#Test if Stock A is equal to 10 and Stock B is equal to 12.
(stock_A==10) & (stock_B==12)

This will return True if both the conditions evaluate to True. The result will be True as shown below:

> (stock_A==10) & (stock_B==12)
[1] True

However, how will this work if we apply this to Numpy arrays.

# The following are two arrays containing returns from two stocks over the past five days.
stock_A = np.array([10, 8, 9, 11, 12])
stock_B = np.array([8,11,10,10,12])

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads