How to condense if/else into one line in Python?

16    Asked by Natunyadav in Python , Asked on May 15, 2025

How can you simplify an if/else statement into a single line in Python? Learn how Python's conditional (ternary) expressions allow you to write concise, readable code by combining logic into one streamlined line.

Answered by Ruth Lambert

In Python, you can condense an if/else statement into a single line using what's called a ternary conditional operator. This is a clean and readable way to assign a value or return a result based on a condition without writing a full multi-line if/else block.

 Syntax:

  value_if_true if condition else value_if_false

 Example:

age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult

 When to Use One-Line If/Else:

  • Simple assignments where both outcomes are straightforward.
  • Return statements inside functions.
  • Inline expressions for cleaner and more readable code.

 When Not to Use:

  • When the logic is complex and readability would suffer.
  • If either the if or else part involves multiple steps or side effects.

 More Examples:

x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)
score = 75
grade = "Pass" if score >= 50 else "Fail"

This approach keeps your code concise without sacrificing clarity—perfect for quick decisions or assignments. Just remember: use it wisely and avoid cramming too much logic into one line if it hurts readability.



Your Answer

Interviews

Parent Categories