If you want to represent If-Else Statements in one single line in Python, you can follow the below syntax.
Syntax:
Let's take a look at a few examples,
Example 1: If the number is even or odd
no = 17
is_even_off = "Even" if no % 2 == 0 else "Odd"
print(is_even_off)
Output:
Example 2: Greeting for California or the rest of USA
state = "California"
greeting_cali = "Welcome to sunny California!"
greeting_usa = "Welcome to the United States!"
greeting = greeting_cali if state == "California" else greeting_usa
print(greeting)
Output:
Welcome to sunny California!
Example 3: If today is a weekday or weekend
import datetime
today = datetime.date.today()
wd = "Weekday"
we = "Weekend"
day_type = wd if today.weekday() < 5 else we
print(f"Hey there! Today is a {day_type}.")

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!