Ternary Operator

Basic Ternary

  1. # ternary syntax: value_if_true if condition else value_if_false
  2. age = 20
  3. status = "Adult" if age >= 18 else "Minor"
  4. #ans: status is "Adult"

Ternary with Numbers

  1. # ternary with numeric values
  2. x = 10
  3. result = "Big" if x > 5 else "Small"
  4. #ans: result is "Big"

Nested Ternary

  1. # ternary inside ternary
  2. score = 85
  3. grade = "A" if score >= 90 else "B" if score >= 80 else "C"
  4. #ans: grade is "B"

Ternary in Assignment

  1. # use in variable assignment
  2. x = 5
  3. y = x * 2 if x > 3 else x + 2
  4. #ans: y is 10 (condition True)

Ternary in Print

  1. # use directly in print
  2. x = 10
  3. print("Even" if x % 2 == 0 else "Odd")
  4. #ans: Even

Exercises - Part 1

  1. # what is result?
  2. x = 10
  3. result = "Big" if x > 5 else "Small"
  4. #ans: "Big"

Exercises - Part 2

  1. # what about this?
  2. x = 0
  3. y = x if x else 10
  4. #ans: 10 (x is falsy)

Exercises - Part 3

  1. # nested ternary?
  2. score = 75
  3. grade = "A" if score >= 90 else "B" if score >= 80 else "F"
  4. #ans: "F" (doesn't match first two conditions)

Exercises - Part 4

  1. # ternary with calculation?
  2. x = 5
  3. y = x * 2 if x > 3 else x + 2
  4. #ans: 10 (condition is True)

Exercises - Part 5

  1. # what is result?
  2. is_valid = True
  3. message = "Valid" if is_valid else "Invalid"
  4. #ans: "Valid"

Exercises - Part 6

  1. # tricky: what happens?
  2. x = 5
  3. y = 10 if x > 3 else 20 if x > 1 else 30
  4. #ans: 10 (first condition True)

Exercises - Part 7

  1. # what is assigned?
  2. x = None
  3. y = x if x is not None else "default"
  4. #ans: "default"

Exercises - Part 8

  1. # boolean ternary?
  2. x = True
  3. result = 1 if x else 0
  4. #ans: 1

Exercises - Part 9

  1. # what is value?
  2. x = -5
  3. abs_x = x if x >= 0 else -x
  4. #ans: 5

Exercises - Part 10

  1. # what happens?
  2. x = []
  3. result = "Full" if x else "Empty"
  4. #ans: "Empty"

Exercises - Part 11

  1. # complex condition?
  2. x, y = 5, 10
  3. result = "Yes" if x > 0 and y > 0 else "No"
  4. #ans: "Yes"

Google tag (gtag.js)