Python offers concise ways to express conditional logic using shorthand if-else statements (ternary operator) and one-line if-elif-else structures using nested ternary operators.
This guide explores these techniques, balancing code brevity with readability.
Shorthand If-Else Statements (Ternary Operator)
The ternary operator in Python provides a compact way to express conditional logic, ideal for simple if-else conditions where the result can be calculated easily without multiple lines of code.
Basic Syntax
The syntax is as follows: value_if_true if condition else value_if_false
variable1 = 50
variable2 = 100
result = 5 if variable1 > variable2 else 10
print(result) # Output: 10Here's the equivalent if-else statement:
variable1 = 50
variable2 = 100
if variable1 > variable2:
result = 5
else:
result = 10
print(result) # Output: 10- The ternary operator makes the code concise, however, the
if-elseis generally easier to read.
You can directly include the ternary operator within a print() call or assign the result to a variable.
print('hello' if len('hi') == 2 else 'bye') # Output: hello
result = 'hello' if len('hi') == 2 else 'bye'
print(result) # Output: hello
name = None
result = 'tom nolan' if not name else name
print(result) # Output: tom nolanOne-Line If-Elif-Else Statements (Nested Ternary Operator)
You can nest ternary operators to create one-line if-elif-else statements, but exercise caution as excessive nesting can hinder readability.
my_str = 'tom nolan'
result = ("Anonymous" if not my_str else my_str.upper()
if len(my_str) > 2 else my_str.capitalize())
print(result) # Output: TOM NOLAN- The outer ternary operator checks if
my_stris empty and returns"Anonymous"if so. - If
my_stris not empty, the nested inner ternary operator checks if its length is greater than 2. - If the length is greater than 2 the uppercase string is returned using
my_str.upper(). - Otherwise, the string is capitalized using
my_str.capitalize(). - You can use parentheses to format nested ternary operators for better readability.
Here's the equivalent using if-elif-else:
my_str = 'tom nolan'
if not my_str:
result = "Anonymous"
elif len(my_str) > 2:
result = my_str.upper()
else:
result = my_str.capitalize()
print(result) # Output: TOM NOLANHere's another example using nested ternaries:
my_num = 50
result = (10 if my_num > 100 else
20 if my_num < 100 else 0)
print(result) # Output: 20
my_num = 50
result = ('a' if my_num > 100 else
('b' if my_num < 100 else 'c'))
print(result) # Output: b