In java script there is an alternative to if statement i mean like ternary operator : (boolean expression )? option 1: option 2
, it is elegant compact and sometimes less confusing. I have searched a lot to find an alternative for 'if' statement in python but i couldn't find anything. Is there any way to trick python so we can avoid if statement ?
Asked
Active
Viewed 442 times
0

Charles Duffy
- 280,126
- 43
- 390
- 441
-
2Thats not an if statement, its a ternary operator. Just do option1 if statement else option2 – Peter Featherstone Jul 23 '17 at 18:17
-
Maybe the keyword you can use is "inline if". There are some already solved questions with that keywords. – gal007 Jul 23 '17 at 18:19
-
I don't mean any inline if statement , the point is avoid any if and else or case and switch – Jul 23 '17 at 18:23
-
1`option1 if condition else option2` **is** how Python spells the same thing that is, in JavaScript, described with the syntax `condition ? option1 : option2`. – Charles Duffy Jul 23 '17 at 18:26
1 Answers
0
If expression:
option1 if boolean_expression else option2

yuri kilochek
- 12,709
- 2
- 32
- 59
-
See "Answer Well-Asked Questions" in https://stackoverflow.com/help/how-to-answer, particularly guiding against answering questions you know are duplicative. – Charles Duffy Jul 23 '17 at 18:27
-
-
1@SamFarjamirad, just because it uses the word "if" doesn't mean it's the same syntax. It's **absolutely** a different thing (different grammar in the parser even if it uses the same keywords). – Charles Duffy Jul 23 '17 at 18:28
-
1@SamFarjamirad yes it is. It's an expression that yields a result, not just causes side effects. – yuri kilochek Jul 23 '17 at 18:30
-
@CharlesDuffy thanks , but i'm already convinced , just one more thing, which one is faster ? – Jul 23 '17 at 18:31
-
@SamFarjamirad, ..."faster"? Neither is necessarily faster. They do different things, as yuri pointed out above, and selection should be made in accordance with which one best models intent. – Charles Duffy Jul 23 '17 at 18:32