What does “variable or 0” mean in python?

后端 未结 4 832
执笔经年
执笔经年 2020-12-09 16:04

What is the meaning of the following statement in python:

x = variable_1 or 0

variable_1 is an object. What value does x

4条回答
  •  Happy的楠姐
    2020-12-09 16:20

    x = variable_1 or 0
    

    It means that if variable_1 evaluates to False (i.e. it is considered "empty" - see documentation for magic method __nonzero__), then 0 is assigned to x.

    >>> variable_1 = 'foo'
    >>> variable_1 or 0
    'foo'
    >>> variable_1 = ''
    >>> variable_1 or 0
    0
    

    It is equivalent to "if variable_1 is set to anything non-empty, then use its value, otherwise use 0".

    Type of x is either type of variable_1 or int (because 0 is int).

提交回复
热议问题