1

I'm trying to figure out how the 'or' operator works in python when used on variables that are not boolean. In particular, I'm puzzled by the fact that it seems to be non-commutative. Shouldn't 'or' be commutative?

From what I can tell it seems to be implementing:

a or b = a, unless a = null or 0, then a or b = b.

Examples:

> 0 or 5  
5
> 5 or 3 
5
> 3 or 5 
3
> '' or 5
5
> 5 or ''
5
> 'ab' or 'cd'
'ab'
> 'cd' or 'ab'
'cd'
> '' or 'cd'
'cd'
Alex Kinman
  • 2,437
  • 8
  • 32
  • 51

1 Answers1

0

From the docs:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

[...]

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

Community
  • 1
  • 1
a_guest
  • 34,165
  • 12
  • 64
  • 118