Flat_Eric Contemplating Data Type Conversions

Ternary Operator

The Ternary Operator

So far we have learned about conditional statements using if, elif, and else. These are powerful tools but sometimes the logic is simple enough that writing a full block feels like overkill. That is where the ternary Ternary" is typically pronounced TUR-nuh-ree, with the emphasis on the first syllable. It sounds similar to "turn-er-ie" or a simplified "tern-ary" (rhyming with "canary") operator comes in.

Also known as a conditional expression, the ternary operator is a shortcut that lets you write a simple if/else statement in a single line. It evaluates a condition and returns one of two values depending on whether that condition is True or False.

The structure in plain English looks like this:

value_if_true if condition else value_if_false

Read it left to right. Give me value_if_true if the condition is True, otherwise give me value_if_false. It is the same logic as a standard if/else block, just written in one line.

It is worth noting that the ternary operator is best used for simple conditions. If your logic requires elif or multiple conditions, a full if/else block is the better choice. Keeping your code readable is always the priority.

ternary operator example

Ternary Operator Examples

For each example below you will see the full if/else version followed by the ternary operator version. Both produce exactly the same result.

Example 1: Positive or Negative

Check whether a number is positive or negative and store the result in a variable.

Example 2: Over 18 Check

Check whether a user meets the minimum age requirement.

Example 3: Item vs Items

Return the correct word depending on how many items are in a cart. This is a very common real world use of the ternary operator.

Example 4: Temperature

Check a temperature value and return a label based on the result.

Example 5: Battery Level

Check a battery level and warn the user if it is running low.

Example 6: File Upload

Check whether a file size is within the allowed limit before uploading.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Pass or Fail

Exercise 2: Stock Check

Exercise 3: Day or Night

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course