+91 81900 98289

Ternary Operator

This Ternary Operator lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A conditional expression chooses one of two values in a single line. Read it as the true value, then if, the test, else, and the other value.

Use it for a short label. Switch to a normal if block when either side needs more than one step.

Example 1: Start here

The test sits in the middle, not at the start.

score = 82 # a whole number band = "pass" if score >= 70 else "retry" # text print(band)

Example 2: Pick one word

The value before if is used when the test is true.

score = 82 # a whole number label = "Pass" if score >= 80 else "Try again" # text print(label)

Example 3: Pick a number

The value after else is used when the test is false.

seats = 0 # a whole number fee = 0 if seats == 0 else 25000 # use the value before if when the test is true print(fee)

Example 4: Use it in print

You can put the same one-line choice directly inside print.

score = 70 # a whole number print("Pass" if score >= 80 else "Try again") # a comparison is True or False
The test sits in the middle, not at the start.
Call Now 81900 98289