If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false. While standard if-else statements span multiple lines, Python allows you to write them in a concise one line as well.
Table of Contents
What are If-Else Statements?
If-else statements allow you to execute different code blocks based on whether a condition is True
or False
. The standard syntax is:
if condition:
# execute if condition is True
else:
# execute if condition is False
The else block is optional. You can have multiple elif blocks for additional conditions.
Now to write the if-else statement in one line we have to use the ternary operator.
What is a Ternary Operator?
The key to writing single line if-else statements in Python is the ternary operator, also known as the conditional expression. The ternary operator has this syntax:
value_if_true if condition else value_if_false
If the condition evaluates to true, the expression returns the value_if_true
, otherwise it returns the value_if_false
.
Writing a Simple One-Line If-Else Statement
Let’s look at a basic example. Say we want to assign a string value to a variable based on whether a number is even or odd:
x = 10
result = "even" if x % 2 == 0 else "odd"
print(result) # Prints "even"
The ternary operator checks if x % 2 == 0
is true, and if so assigns “even” to result. Otherwise, it assigns “odd”.
So the above code checks if x is even, and if so assigns the string “even” to result. If x is odd, it assigns “odd” to result.
Handling Complex Conditions
You can also use ternary operators for more complex multi-condition checks:
y = -5
result = "positive" if y > 0 else ("zero" if y == 0 else "negative")
print(result) # Prints "negative"
Here we nested two ternary operators to handle three possible conditions.
- It first checks if y > 0. If so, it immediately returns “positive”.
- If that fails, it goes to the else and hits the nested ternary operator.
- This checks if y == 0 and returns “zero” if so.
- If both outer conditions fail, the final else returns “negative”.
So it is checking for positive, zero, then negative as the three cases. The nesting allows multiple conditions to be handled.
When to Use One-Line If-Else
One-line if-else statements can be useful for writing simple conditional logic that fits on one line. However, for complex logic, stick to the standard multiline format for readability.
Some cases where one-line if-else works well:
- Simple value assignment based on condition
- Returning value from function based on condition
- Print statement based on condition
Avoid complex nested logic or multiple conditions in one line.
Example Use Cases
Here are some examples of good use cases for one-line if-else:
Assign Variable Based on Condition
# Set status to "approved" if score > 90 else "denied"
status = "approved" if score > 90 else "denied"
Return Value from Function
def get_result(num):
return "pass" if num > 60 else "fail"
Print Message Based on Input
name = input("Enter name: ")
print(name + " is logged in") if name else print("Please enter a name")
Benefits of Ternary Operators
When used properly, ternary operators can:
- Make code more concise
- Improve readability for straightforward logic
- Provide an elegant one-line syntax
However, be careful not to sacrifice too much readability for the sake of brevity.
So in summary, ternary operators are a handy tool for writing compact if-else statements in one line of Python code. Just be sure to use them in moderation to keep your code clean and maintainable.