IntermediateLesson firstCategory 10 of 20

Ternary & Walrus Operator

Write inline conditions and assignment expressions. Read the lesson first, then move through the exercises in order.

7 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Validation Ternary

Study Material

Read the full lesson

Ternary basics

A ternary is a short if/else expression.

python
score = 85 status = "pass" if score >= 60 else "fail"

This is great when the logic is simple and fits on one line.

Default values with a ternary

python
name = input().strip() label = name if name else "Anonymous"

Chained ternary (use carefully)

You can chain ternaries, but it can become hard to read.

python
grade = "A" if score >= 90 else "B" if score >= 80 else "C"

If it feels confusing, use a normal if/elif/else block.

Walrus operator basics

The walrus operator := assigns a value inside an expression. It is available in Python 3.8+.

python
if (n := len("python")) > 3: print(n)

Walrus in loops

It can help when you read input until the user stops.

python
while (line := input()): print("Read:", line)

Common mistakes to avoid

  • Using a ternary for complex logic.
  • Overusing chained ternaries.
  • Using the walrus operator when it makes the code less clear.

What you should understand after this lesson

  • How to write a ternary expression.
  • When a ternary is helpful and when it is not.
  • How to use the walrus operator safely.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.