The Python Oracle

Python operator that mimic javascript || operator

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Python Operator That Mimic Javascript || Operator
00:22 Accepted Answer Score 31
00:45 Answer 2 Score 3
00:59 Answer 3 Score 1
01:08 Answer 4 Score 3
01:25 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.