xxxxxxxxxx
if 1==1 or 1==2:
print("this is true")
#this is distinct from the || seen in some other languages
xxxxxxxxxx
#Python (Basic) Logical Operators
------------------------------------------
OPERATOR | SYNTAX |
----------------------
and | a and b |
----------------------
#Example-----------------------------------
if condition1 and condition2 and condition3:
all_conditions_met == true
else:
all_conditions_met == false
------------------------------------------
OPERATOR | SYNTAX |
----------------------
or | a or b |
----------------------
#Example
if condition1 or condition2 or condition3:
any_condition_met == true
else:
any_condition_met == false
------------------------------------------
OPERATOR | SYNTAX |
----------------------
not | not a |
----------------------
if not equal_to_condition:
equal_to_condition == false
else:
equal_to_condition == true
xxxxxxxxxx
>>> s1 = {"a", "b", "c"}
>>> s2 = {"d", "e", "f"}
>>> # OR, |
>>> s1 | s2
{'a', 'b', 'c', 'd', 'e', 'f'}
>>> s1 # `s1` is unchanged
{'a', 'b', 'c'}
>>> # In-place OR, |=
>>> s1 |= s2
>>> s1 # `s1` is reassigned
{'a', 'b', 'c', 'd', 'e', 'f'}
xxxxxxxxxx
children_above_five= True
have_good_health= True
if children_above_five and have_good_health:
print("Eligible to get admission in Primary school.")
children_above_five= True
have_good_health= False
if children_above_five or have_good_health:
print("Eligible to get admission in Primary school.")
children_above_five= True
have_good_health= False
if children_above_five and not have_good_health:
print("Eligible to get admission in Primary school.")
xxxxxxxxxx
a = 3
b = 4
# Arithmetic Operators
print("The value of 3+4 is ", 3+4)
print("The value of 3-4 is ", 3-4)
print("The value of 3*4 is ", 3*4)
print("The value of 3/4 is ", 3/4)
# Assignment Operators
a = 34
a -= 12
a *= 12
a /= 12
print(a)
# Comparison Operators
# b = (14<=7)
# b = (14>=7)
# b = (14<7)
# b = (14>7)
# b = (14==7)
b = (14!=7)
print(b)
# Logical Operators
bool1 = True
bool2 = False
print("The value of bool1 and bool2 is", (bool1 and bool2))
print("The value of bool1 or bool2 is", (bool1 or bool2))
print("The value of not bool2 is", (not bool2))
xxxxxxxxxx
fruit = 'banana'
print('n' in fruit) # Output: True
print('m' in fruit) # Output: False
print('nan' in fruit) # Output: True
if 'b' in fruit:
print('Found it') # Output: Found it
xxxxxxxxxx
# usual form
a and b == c
# sometimes usefull to make up expressions
import operator
from itertools import reduce
# equals to `a and b and c`
reduce(
operator.and_,
[a, b, c]
)