Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operator that mimic javascript || operator

Tags:

python

I am Python newbie, so maybe don't knew if this is obvious or not.

In Javascript a||b returns a if a is evaluated to true, else returns b. Is that possible in Python other than lengthy if else statement.

like image 437
Gagandeep Singh Avatar asked Nov 13 '11 12:11

Gagandeep Singh


1 Answers

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
like image 119
Tadeck Avatar answered Oct 22 '22 10:10

Tadeck