Enrollments Open for Advanced Certification Courses on Data Science, ML & AI by E&ICT Academy IIT Roorkee
Apply NowThere are 3 logical operators in Python: and
, or
, and not
. The meaning of these operators is similar to their meaning in English.
3 < 4 and 4 > 1
It returns True
x % 2 == 0 or x % 4 == 0
It returns True
if either of the conditions is true, i.e. if the number x is divisible by 2
or 4
.
The not
operator negates a boolean expression, so,
not (a > b )
It returns True
if a > b is false i.e. if a is less than or equal to b.
Generally, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True
.
23 and True
It returns True
.
While processing a logical expression such as x >= 2 and (x/y) > 2
, Python evaluates the expression from left to right. Because of the definition of and
, if x is less than 2, the expression x >= 2
is False
and so the whole expression is False
regardless of whether (x/y) > 2
evaluates to True
or False
.
So, when there is nothing to be profitable by evaluating the rest of a logical expression, it stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation of a logical expression stops because the overall value is already known, it is called short-circuiting the evaluation.
Short-circuiting helps in creating a guard. For eg,
if y != 0 and x/y:
print("Correct")
Here, y != 0
acts as a guard to ensure that we only execute (x/y)
if y is non-zero because division by 0 would give an error.
No hints are availble for this assesment
Answer is not availble for this assesment
Loading comments...