The Python Oracle

Python operator that mimic javascript || operator

This video explains
Python operator that mimic javascript || operator

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Question
00:32 Accepted answer (Score 26)
01:03 Answer 2 (Score 3)
01:27 Answer 3 (Score 3)
01:49 Answer 4 (Score 1)
02:01 Thank you

--

Full question
https://stackoverflow.com/questions/8111...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 31


I believe this is correct:

x = a or b

Proof

This is how "||" works in JavaScript:

> 'test' || 'again'
"test"
> false || 'again'
"again"
> false || 0
0
> 1 || 0
1

This is how "or" works in Python:

>>> 'test' or 'again'
'test'
>>> False or 'again'
'again'
>>> False or 0
0
>>> 1 or 0
1



ANSWER 2

Score 3


In python you can use something like this

result = a or b

which may give you result=a if a is not False (ie not None, not empty, not 0 length), else you will get result=b




ANSWER 3

Score 3


You can simply do

a or b

For more complex logic (only for Python 2.5 and above):

x if a > b else y

This is the equivalent to the following which you may be familiar with from Javascript:

a > b ? x : y;



ANSWER 4

Score 1


x = a or b does the same thing.