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
- Write the True value.
- Write
ifand the condition. - Write
elseand 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.
Ravindra Bagale's Tip – मराठी
One-line if लांब होऊ लागला तर साध्या if/else वर परत या. हुशार code पेक्षा स्पष्ट code चांगला.
Ravindra Bagale's Tip – हिंदी
One-line if लंबा होने लगे तो सादे if/else पर लौट आओ. चालाक code से साफ़ code बेहतर.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.