W WolfCode · CSC 141

Walkthrough: Sign of a Number

例题: 数的正负号

≈ 8 min · python-conditionals · Open in WolfCode

Three mutually exclusive outcomes → if / elif / else. The simplest possible 'chained conditional' from Think Python §5.5, end-to-end.

The problem

Write sign(n) so that it returns "positive", "negative", or "zero" depending on n. This is a worked example (kind = example): read it, run it, modify it. The autograder will pass without any changes.

The pattern

Click ▶ Run — predict the output first

Why not three separate ifs?

A common beginner version works only because each branch has a return — but it does extra checks and is easier to break with a refactor:

Works but wastes effort

The elif version makes the intent explicit: these are alternatives, not three independent questions.

Trace it by hand

  • n = 5 → first condition true → returns "positive"
  • n = -3 → first false, second true → returns "negative"
  • n = 0 → both conditions false → else fires → returns "zero"

Next

Open the next lesson — Letter Grade — which uses the exact same pattern but with five branches and an order-of-branches trap.