Ternary Statements & Dictionaries

Learn to use ternary statements and dictionaries in Python with Transcrypt.

Ternary statements

With functional programming like we are doing with React, it’s convenient to create inline logical branching expressions for the simple True/False type of conditions. JavaScript has a ternary operator that does just that. It takes a boolean expression that will either evaluate to True or False, followed by a question mark ?. It will return a value if the expression is True, and return another value if the expression evaluates to False, separated by a colon :. In our example, there is a ternary expression that determines what text shows up in the UI based on the value of editTask:

{this.state.editTask ? "Edit Task: " : "Add Task: "}

Python has the same thing, though it is not quite as terse as the JavaScript ternary operator. It is essentially an inline if-else statement:

"Edit Task: " if editTask is not None else "Add Task: "

The first clause is the result of the expression if it is True. The clause after the if keyword is the boolean expression to evaluate. The clause after the else keyword is the value to return if the expression evaluates to False.


Get hands-on with 1200+ tech skills courses.