A certainl part of an if() structure never gets executed.

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 12 21:55:48 EDT 2013


On Wed, 12 Jun 2013 14:17:32 +0300, Νικόλαος Κούρας wrote:

> doesn't that mean?
> 
> 		if '=' not in ( name and month and year ):
> 
> if '=' does not exists as a char inside the name and month and year
> variables?
> 
> i think it does, but why it fails then?

No. Python is very close to "English-like", but not exactly, and this is 
one of the easiest places to trip.

In English:

"the cat is in the box or the cupboard or the kitchen"

means:

"the cat is in the box, or the cat is in the cupboard, or the cat is in 
the kitchen".


But that is not how Python works. In Python, you have to say:

cat in box or cat in cupboard or cat in kitchen


Although this will work as well:

any(cat in place for place in (box, cupboard, kitchen)) 


In Python, an expression like this:

cat in (box or cupboard or kitchen)


has a completely different meaning. First, the expression in the round 
brackets is evaluated:

(box or cupboard or kitchen)


and then the test is performed:

cat in (result of the above)


The expression (box or cupboard or kitchen) means "return the first one 
of box, cupboard, kitchen that is a truthy value, otherwise the last 
value". Truthy values are those which are considered to be "like True":

truthy values:

- True
- object()
- numbers apart from zero
- non-empty strings
- non-empty lists
- non-empty sets
- non-empty dicts
- etc.

falsey:

- False
- None
- zero (0, 0.0, Decimal(0), Fraction(0), etc.)
- empty string
- empty list
- empty set
- empty dict
- etc.

(Can you see the pattern?)


So you can experiment with this yourself:

42 or 23 or "foo"
=> the first object is truthy, so it is returned

0 or 23 or "foo"
=> the first object is falsey, and the second object is truthy, 
so it is returned

0 or [] or "foo"
=> the first two objects are falsey, so the third is returned


The "and" operator works in a similar fashion. Experiment with it and see 
how it works for yourself.



-- 
Steven



More information about the Python-list mailing list