+ 5

Ternary conditional operator

Does python have ternary conditional operator?

25th Feb 2021, 6:27 AM
Roza Simonyan
Roza  Simonyan - avatar
9 odpowiedzi
+ 16
Yes, it was added in version 2.5. Here you can see syntax: a if condition else b
25th Feb 2021, 6:39 AM
Davit Baghoyan
Davit Baghoyan - avatar
25th Feb 2021, 6:38 AM
Nikolai Ivanov
Nikolai Ivanov - avatar
+ 3
Roza Simonyan No. but you can try like this a = 10 b = 20 min = a if a < b else b print (min)
25th Feb 2021, 6:34 AM
A͢J
A͢J - avatar
+ 2
Yes python has a ternary conditionnal operator to avoid more redability of a code
9th Sep 2022, 7:35 PM
Excellence Kawej
Excellence Kawej - avatar
+ 1
no 'clasic' short conditional operator, but you could write onelined assignable if..else: value = 42 if condition else 0
25th Feb 2021, 6:37 AM
visph
visph - avatar
+ 1
It can use python ternary operator in list comprehension my_list = list(range(1,11)) result = ['yes' if a%10==0 else 'No'] The statement inside the list is an example of python ternary operator
7th Jul 2021, 1:01 AM
Chiazam OCHIEGBU
Chiazam OCHIEGBU - avatar
+ 1
Simple if else statements
16th Feb 2022, 1:27 PM
Uttam Pipaliya
Uttam Pipaliya - avatar
+ 1
Simple answer. Passes all test cases. Change nothing. Add this in side code instead and to_cash >=500 #"and" as you know, makes another condition to follow. Like, this AND that. The rest is already written. Thank you for reading ❤️ I hope this helps
25th Feb 2022, 8:09 PM
Chelsie Herr
Chelsie Herr - avatar
+ 1
A complex sample: age = int(input()) print("baby" if age<1 else "toddler" if age<3 else "preschool" if age <5 else "grade school" if age<12 else "teen" if age<18 else "young adult" if age <21 else "adult" if age<39 else "middle aged" if age<59 else "old") 😀
7th Jun 2022, 6:27 PM
Behzad Soleimani Neysiani
Behzad Soleimani Neysiani - avatar