you can do this :-
[condition] and [expression_1] or [expression_2] ;
Example:-
print(number%2 and "odd" or "even")
This would print "odd" if the number is odd or "even" if the number is even.
Note :- 0 , None , False , emptylist , emptyString evaluates as False. And any data other than 0 evaluates to True.
if the condition [condition] becomes "True" then , expression_1 will be evaluated but not expression_2 . If we "and" something with 0 (zero) , the result will always to be fasle .So in the below statement ,
0 and exp
The expression exp won't be evaluated at all since "and" with 0 will always evaluate to zero and there is no need to evaluate the expression . This is how the compiler itself works , in all languages.
In
1 or exp
the expression exp won't be evaluated at all since "or" with 1 will always be 1. So it won't bother to evaluate the expression exp since the result will be 1 anyway . (compiler optimization methods).
But in case of
True and exp1 or exp2
The second expression exp2 won't be evaluated since True and exp1
would be True when exp1 isn't false .
Similarly in
False and exp1 or exp2
The expression exp1 won't be evaluated since False is equivalent to writing 0 and doing "and" with 0 would be 0 itself but after exp1 since "or" is used, it will evaluate the expression exp2 after "or" .
Note:- This kind of branching using "or" and "and" can only be used when the expression_1 doesn't have a Truth value of False (or 0 or None or emptylist [ ] or emptystring ' '.) since if expression_1 becomes False , then the expression_2 will be evaluated because of the presence "or" between exp_1 and exp_2.
In case you still want to make it work for all the cases regardless of what exp_1 and exp_2 truth values are, do this :-
[condition] and ([expression_1] or 1) or [expression_2] ;