Member-only story
Only Truly Pythonista Knows How to Write if-else WHITOUT if-else keywords in 7 different ways
5 min readMar 9, 2025
Okay, you say you love Python, but do you know how to write if-else without the if-else keywords in different ways?
Here is a funny challenge. If you know all of the following code, I will call you a true Pythonista.
Basic way: if else
The most basic way to write if-else is using if-else directly:
import random
age = random.randint(1, 30)
message = ''
if age > 18:
message = f'{age} is adult'
else:
message = f'{age} is minor'
print(message)
Every programmer knows this code.
Pythonic code
But in Python, we prefer the Pythonic code style. Here is an improvement:
import random
age = random.randint(1, 30)
message = f'{age} is adult' if age > 18 else f'{age} is minor'
print(message)
More concise and more readable. It’s fine.
Now the true challenge comes: Are there any other ways to write if-else?
Short Circuit
import random
age = random.randint(1, 30)
message = age > 18 and f'{age} is adult' or f'{age} is minor'
print(message)