alwbtc
alwbtc

Reputation: 29455

What does "variable or 0" mean in python?

What is the meaning of the following statement in python:

x = variable_1 or 0

variable_1 is an object. What value does x have above? And what is the type of x?

Upvotes: 28

Views: 15126

Answers (4)

sloth
sloth

Reputation: 101072

If variable_1 evaluates to False , x is set to 0, otherwise to variable_1

Think of it as

if variable_1:
  x = variable_1
else:
  x = 0

Upvotes: 30

kmerenkov
kmerenkov

Reputation: 2889

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).

Upvotes: 2

rxdazn
rxdazn

Reputation: 1390

x will be initialized to variable_1 if its value is not None or False

simple exemple :

>>> a = None
>>> b = 2
>>> a or 0
0
>>> b or 0
2

Upvotes: 4

jamylak
jamylak

Reputation: 133584

x will be 0 if variable_1 evaluates as false, otherwise it will be variable_1

>>> 'abc' or 0
'abc'
>>> '' or 0
0
>>> ['a', 'b', 'c'] or 0
['a', 'b', 'c']
>>> [] or 0
0

Upvotes: 22

Related Questions