Sling Academy
Home/Python/Shorthand syntax for if/else in Python (conditional expression)

Shorthand syntax for if/else in Python (conditional expression)

Last updated: July 15, 2023

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!

Next Article: Making use of the “with” statement in Python (4 examples)

Previous Article: Python While Loops: Tutorial & Examples

Series: Control Flow & Functions in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots