Name

Conditional Expressions

Examples
s = 0
for i in range(5, 100, 5):
    s = 0 if i < 50 else 255
    stroke(s)
    line(30, i, 80, i)
Description A shortcut for writing an if and else structure. Conditional expressions in Python take the form expression1 if test else expression2. If the test evaluates to True, expression1 is evaluated and returned. If the condition evaluates to False, expression2 is evaluated and returned.

The following conditional expression:
result = expression1 if test else expression2

is equivalent to this structure:
if test:
result = expression1
else:
result = expression2
Syntax
expression1 if test else expression2
Parameters
testany valid expression which evaluates to True or False
expression1any valid expression
expression2any valid expression
Related if
else

Updated on Tue Feb 27 14:07:12 2024.

If you see any errors or have comments, please let us know.