15

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.

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Basically it could be explained by showing these two statements as having the same effect: result = a or b, result = a if a else b (or longer: if a: result = a [line break] else: result = b). Upvoting anyway (for being correct).
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;

Comments

1

x = a or b does the same thing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.