Conditional Expression - Ternary Operation

This section provides a quick introduction on conditional expression, which tests a Boolean object and returns one of two given objects.

What Is Conditional Expression? A conditional expression is a special expression that tests a Boolean object and returns one of two given objects.

A conditional expression is also called a ternary operation, because it requires 3 operands:

operand_1 if operand_2 else operand_3

where:
  operand_2 is the condition object
  operand_1 is evaluated and returned, if operand_2 is True
  operand_3 is evaluated and returned, if operand_2 is False

Here are two examples of conditional expressions:

>>> 'Yes' if 1/3 > 0.3333333333333 else 'No'
'Yes'

>>> 'Yes' if 1/3 > 0.3333333333333333333 else 'No'
'No'

Ternary operations have a precedence lower that Boolean OR:

Symbols                Operations
--------------------   --------------
...
not                    Boolean NOT
and                    Boolean AND
or                     Boolean OR
if ... else            Ternary operation

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

Variables, Operations and Expressions

 What Is Variable

 What Is Operation

 What Is Expression

Conditional Expression - Ternary Operation

 Assignment Expression - Walrus Operation

 Statements - Execution Units

 Function Statement and Function Call

 Iterators and Generators

 List, Set and Dictionary Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB