Python: If Else Statements in One Single Line

If you want to represent If-Else Statements in one single line in Python, you can follow the below syntax.


the_value_if_true if condition else the_value_if_false

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"



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

Welcome to sunny California!

Example 3: If today is a weekday or weekend

import datetime

today =
wd = "Weekday"
we = "Weekend"

day_type = wd if today.weekday() < 5 else we

print(f"Hey there! Today is a {day_type}.")
Python If Else condition in one line

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap