hans-t
hans-t

Reputation: 3233

Conditional statement with empty string

Why does '' and not '123' evaluate to '' instead of False, but not '123' and '' evaluates to False in Python 3.4.3?

Upvotes: 2

Views: 227

Answers (1)

John1024
John1024

Reputation: 113964

The logical and/or operators stop evaluating terms (short-circuit) as soon as the answer is decided.

Examples with and

>>> '' and not '123'
''

The first one is false, so the and is short-circuited and the first one is returned.

>>> not '123' and ''
False

not '123' returns False. Since that is false, the and is short-circuited and the result of not '123' one is returned.

For exactly the same reason, the following returns zero:

>>> 0 and '123'
0

And the following returns []:

>>> [] and '123'
[]

Examples with or

>>> '' or '123'
'123'
>>> not '123' or 'Hi'
'Hi'
>>> '123' or 'Hi'
'123'

Documentation

This behavior is specified in the documentation where:

  • x or y is defined as if x is false, then y, else x

  • x and y is defined as if x is false, then x, else y

  • not x is defined as if x is false, then True, else False

Upvotes: 2

Related Questions