python logical operators

Logical operators

Logical operators are used to determine, whether the relationship between the phases is false or true.


Returns True or False depending on the relationship of the phases.


Python basically has 3 logical operators.


OperatorOperation
andLogical AND
orLogical OR
notLogical NOT


Logical and operator

In and operator, when the two phases are true then only this operation is true or returns True.


For example:- 'Imagine you are going to a picnic and you are taking Apples and Mangos with you'.
To tell your mother that you are taking Apples as well as Mangos, you used 'and' to specify that you want both Apples and Mangos.
"Then only you will go to the picnic".

Program 

>>> 3>2 and 2<3
True
>>> 3<2 and 2>3
False
>>> 3==3 and 3<2
False

The 3rd command in this program is '3==3 and 3<2', the first relation is true and the 2nd relation is false and that's the reason we got 'False'.


Logical or operator

In or operator, the operation performed is true or returns True, when either one of the phases are true.


This operation returns or is false, only when both the phases are false. 


For example:- 'Again Imagine you are going to a picnic and you are taking Apples or Mangos with you'.
To tell your mother that you are taking either one of them, Apples or Mangos, you will use 'or' to specify that you want either Apples or Mangos.
"If you don't take both, then there will not be any kind of picnic".

Program 

>>> 3<2 or 2>3
False
>>> 3==3 or 3<2
True
>>> 3==3 or 2==2
True

The 2rd command in this program is '3==3 or 3<2', the first relation is true and the 2nd relation is false and that's the reason we got 'True'.


Logical not operator

Returns the opposite of the result. If the result is True then it returns False and if the result is False it will returns True.


Program 

>>> not 3 == 3
False
>>> (3 == 3 and 3<2)
False
>>> not(3 == 3 and 3<2)
True
>>> 3 == 3 or 3<2
True
>>> not(3 == 3 or 3<2)
False


In this program the 1st command is 'not 3 == 3', the result of  '3 == 3'is True and due to the 'not' operator we got False.








Conclusion

Logical operators are used to determine, whether the relationship between the phases is false or true. 

Following are the logical operators in Python.

  1. In and operator, when the two phases are true then only this operation returns or is true.

  2. In or operator, the operation performed returns or is true, when either one of the phases are true.

  3. The not operator returns the complement.






Previous                          Next

If you have any query, feel free to ask.

إرسال تعليق

If you have any query, feel free to ask.

Post a Comment (0)