likith
likith

Reputation: 11

How to write 3 conditions in ternery operator of python?

my problem is to use elif in this ternary operator like i want to use 3 conditions in ternary operator

a = 3
if a>0:
    print("is odd" if a %2 !=0  else "is even")

Make a code which return 3 strings one for its odd one for its even and atlast for its zero

Upvotes: 1

Views: 84

Answers (2)

Darshil Jani
Darshil Jani

Reputation: 860

You can check for a condition within a condition. In this case, it will first check whether the value is zero or not. If not zero, then it will move on to check the else condition, which checks the condition inside it for odd or even.

a=3
print("zero" if a==0 else "even" if a%2==0 else "odd")

Upvotes: 0

Martin Cook
Martin Cook

Reputation: 749

print("atlast" if x == 0 else "even" if x%2 == 0 else "odd")

(Thanks Ignatius Reilly for pointing out that I don't need inner parentheses)

Upvotes: 3

Related Questions