# ternary syntax: value_if_true if condition else value_if_falseage = 20status = "Adult" if age >= 18 else "Minor"#ans: status is "Adult"
# ternary with numeric valuesx = 10result = "Big" if x > 5 else "Small"#ans: result is "Big"
# ternary inside ternaryscore = 85grade = "A" if score >= 90 else "B" if score >= 80 else "C"#ans: grade is "B"
# use in variable assignmentx = 5y = x * 2 if x > 3 else x + 2#ans: y is 10 (condition True)
# use directly in printx = 10print("Even" if x % 2 == 0 else "Odd")#ans: Even
# what is result?x = 10result = "Big" if x > 5 else "Small"#ans: "Big"
# what about this?x = 0y = x if x else 10#ans: 10 (x is falsy)
# nested ternary?score = 75grade = "A" if score >= 90 else "B" if score >= 80 else "F"#ans: "F" (doesn't match first two conditions)
# ternary with calculation?x = 5y = x * 2 if x > 3 else x + 2#ans: 10 (condition is True)
# what is result?is_valid = Truemessage = "Valid" if is_valid else "Invalid"#ans: "Valid"
# tricky: what happens?x = 5y = 10 if x > 3 else 20 if x > 1 else 30#ans: 10 (first condition True)
# what is assigned?x = Noney = x if x is not None else "default"#ans: "default"
# boolean ternary?x = Trueresult = 1 if x else 0#ans: 1
# what is value?x = -5abs_x = x if x >= 0 else -x#ans: 5
# what happens?x = []result = "Full" if x else "Empty"#ans: "Empty"
# complex condition?x, y = 5, 10result = "Yes" if x > 0 and y > 0 else "No"#ans: "Yes"
Google tag (gtag.js)