Python Tutorials - Herong's Tutorial Examples - v2.15, by Herong Yang
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
►Variables, Operations and Expressions
►Conditional Expression - Ternary Operation
Assignment Expression - Walrus Operation
Function Statement and Function Call
List, Set and Dictionary Comprehensions
Packages and Package Directories
"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