Ravindra BagaleCourses & study guides मराठी Track your progress

Python if, elif and else Statements with Real Examples for Beginners

P5.5 One-Line if (Conditional Expression) in Python

Why. For a simple choice between two values, a one-line form is shorter and easy to read.

What. value_if_true if condition else value_if_false

How.

Write a one-line if

  1. Write the True value.
  2. Write if and the condition.
  3. Write else and the False value.

Worked example A — Pass or fail.

Step 1 — What we do. A training institute in Pune marks a quiz score.

Step 2 — Type and run this code.

score = 68
result = "Pass" if score >= 70 else "Fail"
print(result)

Step 3 — Output you should see.

Fail

Step 4 — What it means. 68 is below 70, so Fail. Use this only for simple two-way choices.

Worked example B — Currency label.

Step 1 — What we do. We pick a symbol by country code.

Step 2 — Type and run this code.

country = "UK"
symbol = "£" if country == "UK" else "$"
print(symbol + "250")

Step 3 — Output you should see.

£250

Step 4 — What it means. Short and readable. For three or more choices, go back to elif or a dictionary.

Ravindra Bagale's Tip

If a one-line if gets long, switch back to normal if/else. Clear code beats clever code.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.