← Back to Blog

Ternary Mini Project — Your ticket, your price

The problem...

You've already built the ticket pricing system. You know how it works.

Now rewrite it — with ternary where it makes sense. And see exactly where it stops making sense.

The original

age = int(input("Enter your age: "))
window = input("Window seat? (y/n): ")

if age < 12:
    category = "Child"
    price = 5
elif age >= 65:
    category = "Senior"
    price = 8
else:
    category = "Adult"
    price = 12

if window.lower() == "y" and age >= 12:
    price += 3

print(f"{category} ticket — {price} EUR")

Your mission

Rewrite the category and window seat logic using ternary where possible. Keep the price logic separate.

The solution

age = int(input("Enter your age: "))
window = input("Window seat? (y/n): ")

# Category — ternary works, but look at it carefully
category = "Child" if age < 12 else "Senior" if age >= 65 else "Adult"

# Price — ternary works cleanly here
price = 5 if age < 12 else 8 if age >= 65 else 12

# Window seat — clean ternary
price += 3 if window.lower() == "y" and age >= 12 else 0

print(f"{category} ticket — {price} EUR")

What happened?

Category and price — ternary technically works. But read that line again.

category = "Child" if age < 12 else "Senior" if age >= 65 else "Adult"

It's the nested ternary you were warned about. It works. It's not unreadable. But it's on the edge.

The window seat line, on the other hand — clean.

price += 3 if window.lower() == "y" and age >= 12 else 0

One condition. Two outcomes. Exactly what ternary is for.

The lesson

Ternary is not always better. It's better when the condition is simple and the line stays readable. The moment you squint — use the full form.

What you should understand now

  • Ternary can replace simple if / else — not always elif
  • Nested ternaries work but hurt readability — use with caution
  • The window seat line is the ideal use case — one condition, two outcomes
  • When in doubt — full if / else wins
[ login to bookmark ] // copied! 33 views · 1 min
// resources
Exercise ticket_pricing_2.py
← prev if / else — but faster, on one line next → The loop that does the work for you
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.