Python ternary operators

Ternary operators, also known as conditional expressions, provide a shorter syntax for writing an if-else statement in Python. Here's how they work.

TLDR - The Syntax:

value_if_true if condition else value_if_false

This structure first checks the condition. If it's True, the expression returns value_if_true. Otherwise, it returns value_if_false.

Examples:

  1. Let's determine the smallest of two numbers:
a = 10
b = 20
smallest = a if a < b else b
print(smallest) # 10
  1. Now let's write a single line of code to check if a number is even or odd:
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result) # Odd

Ternary operators are a powerful tool that can make your Python code more concise and readable. Just remember: if the logic becomes too complex, a traditional if-else statement might be easier to understand.