In Python, the shorthand syntax for an if/else
statement is called a conditional expression or a ternary operator. It allows you to write a concise one-liner to evaluate a condition and choose one of two values based on the result of that condition.
What is the Point?
The syntax of the conditional expression is as follows:
value_if_true if condition else value_if_false
Explanation of the syntax:
condition
: The expression that is evaluated to determine which value to choose.value_if_true
: The value returned if the condition is true.value_if_false
: The value returned if the condition is false.
For example, you can write:
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)
Instead of:
x = 10
if(x % 2 == 0):
result = "Even"
else:
result = "Odd"
print(result)
Nested shorthand if/else/elif
The shorthand syntax can also be nested to create a shorthand elif
statement, but this is not recommended as it reduces readability and may cause errors. The syntax for a nested shorthand if/else/elif in Python is:
value_if_true_1 if condition_1 else value_if_true_2 if condition_2 else value_if_false
Where condition_1
and condition_2
are any expressions that evaluate to boolean values, value_if_true_1
is the value to return if condition_1
is true, value_if_true_2
is the value to return if condition_1
is false and condition_2
is true, and value_if_false
is the value to return if both conditions are false (again, you should refrain from using this syntax as it is very error-prone and difficult to debug).
Example:
import random
a = random.randint(0, 10)
b = random.randint(0, 10)
x = "A" if a > b else "B" if a == b else "C"
print(x)
The code snippet above is equivalent to this:
import random
a = random.randint(0, 10)
b = random.randint(0, 10)
if a > b:
x = "A"
elif a == b:
x = "B"
else:
x = "C"
print(x)
More examples
Some more practical examples that demonstrate the beauty and conciseness of conditional expression in Python.
Checking if a string is empty or not
The code:
text = "Welcome to Sling Academy!"
message = "Text is empty" if len(text) == 0 else "Text is not empty"
print(message)
Output:
Text is not empty
Converting a boolean value to its string representation
The code:
is_valid = True
status = "Valid" if is_valid else "Invalid"
print(status)
Output:
Valid
Assigning a default value if a variable is None
The code:
value = None
result = value if value is not None else "Default Value"
print(result)
Output:
Default Value
This tutorial ends here. Happy coding & have a nice day!