Returning using a shortened if else statement in Python

python

Solution

The form

print("Yes") if x == 1 else print("No")

is not generally considered Pythonic, since `... if ... else ...` is an expression and you're throwing away the value that the expression produces (always `None`). You can use `print("Yes" if x == 1 else "No")` which is Pythonic since the value of the conditional expression is used as the argument to `print`.

The form

return total if x == 1 else return half

cannot work since `return` is a statement and must occur at the beginning of a logical line. Instead, use

return total if x == 1 else half

(which is parsed the same as `return (total if x == 1 else half)`).

The code

 print(total) if x == 1 else print(half) if x == 2

wouldn't work either - the conditional expression is `... if ... else ...`, i.e. each `if` must be paired with an else that follows it; your second `if` is missing the `else` clause; you could use

 print(total) if x == 1 else print(half) if x == 2 else print('something else')

Again, this wouldn't be considered very pythonic; but you could use

 print(total if x == 1 else half if x == 2 else 'something else')

not that it would be much better either.

Finally, if you're participating in a code golf

print("Yes" if x == 1 else "No")

can be shortened to

print(('No', 'Yes')[x == 1])

by using the fact that `True == 1` and `False == 0` and using these to index a tuple.

Problem

I was going through ways of shortening a normal `if else` statement. One of the formats I found was to change this: ``` if x == 1: print("Yes") else: print("No") ``` Into this: ``` print("Yes") if x == 1 else print("No") ``` Is the code above considered pythonic? Otherwise, what would be a pythonic way of shortening the `if else` statement? I also tried using `return` instead of `print`. I tried ``` return total if x == 1 else return half ``` which resulted in an unreachable statement for the 2nd `return`. Is there a way of doing it that i'm not able to see? Finally, I tried to use an `else if` instead of an `else` with the code, but that wouldn't work either. ``` print(total) if x == 1 else print(half) if x == 2 ``` The code above probably looks stupid logic-wise. Am I missing out on the proper format, or is it really not possible to do `return` and `else if` with this format?

Original source