You might be familiar with the If-Else
statements, and executing both parts of the statement based on the result of the test condition. Consider you’re writing a script and determining the value of many variables depending on whether certain conditions are True
or False
.
a = 30
b = 45
c = 66
if a % 5 == 0: # This evaluates to True.
x = a * 2
else:
x = a / 2
if b / 2 == 10: # This is False.
y = 0
else:
y = b + 5
if c / 3 == 22: # Finally, this evaluates to True.
z = 'Cheesy!'
else:
z = 'No cheese for you!'
Ternary Operators effectively reduce the code footprint of an If-Else
statement from four lines to just one! You are able to evaluate a test condition and assign a variable in a single line with ternary operators. The framework for ternary operators in Python are as follows:
var = <<value_if_true>> if true_expression else <<default_value>>
Knowing this, we can rewrite the previously shown code block to:
a = 30
b = 45
c = 66
x = a * 2 if a % 5 == 0 else a / 2
y = 0 if b / 2 == 10 else b + 5
z = 'Cheesy!' if c / 2 == 22 else 'No cheese for you!'
You can easily tell how much more compact (and cleaner) the code looks when you compress these simple If-Else
statement and use ternary operators instead! Are there any Python/Software Engineering concepts that you are curious about? Tell me which ones in the comments below!