"what is this “and” statement actually doing in the return?" Code Answer

3

in python, both and and or will return one of their operands. with or, python checks the first operand and, if it is a "truthy" value (more on truthiness later), it returns the first value without checking the second (this is called boolean shortcut evaluation, and it can be important). if the first is "falsey", then python returns the second operand, no matter what it is:

python 2.7.3 (default, jan  2 2013, 13:56:14)
[gcc 4.7.2] on linux2
type "help", "copyright", "credits" or "license" for more information.
>>> 2 or 3
2
>>> 0 or 3
3

with "and", much the same thing happens: the first operand is checked first, and if it is "falsey", then python never checks the second operand. if the first operand is "truthy", then python returns the second operand, no matter what it is:

>>> 2 and 3
3
>>> 0 and 3
0
>>> 3 and 0
0
>>> 3 and []
[]
>>> 0 and []
0

now let's talk about "truthiness" and "falsiness". python uses the following rules for evaluating things in a boolean context:

  • the following values are "falsey": false, none, 0 (zero), [] (the empty list), () (the empty tuple), {} (the empty dict), an empty set, "" (the empty string)
  • everything else is "truthy"

so something like password and pass_re.match(password) is taking advantage of python's short-circuit evaluation. if password is none, then the and operator will just return none and never evaluate the second half. which is good, because pass_re.match(none) would have thrown an exception. watch this:

>>> 3 or []
3
>>> [] or 3
3
>>> 0 or []
[]
>>> [] or 0
0
>>> 0 and []
0
>>> [] and 0
[]

see how the short-circuiting is working? now watch this:

>>> value = "hello"
>>> print (value.upper())
hello
>>> print (value and value.upper())
hello
>>> value = none
>>> print (value.upper())
traceback (most recent call last):
  file "<stdin>", line 1, in <module>
attributeerror: 'nonetype' object has no attribute 'upper'
>>> print (value and value.upper())
none

see how the short-circuiting feature of and helped us avoid a traceback? that's what's going on in this function.

By Waqar Alamgir on April 4 2022

Answers related to “what is this “and” statement actually doing in the return?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.