Checking a Wind Range With &&
Ruth’s chain had two postponed branches, one for too little wind and one for too much. She
merges them, so the racing test reads like the club’s rule: the fleet races when the wind is
from 6 knots up to, but not including, 25, in one chained comparison. The else picks the
reason with a conditional expression:
wind_knots = 4
gust_knots = 7
if gust_knots >= 30:
decision = "cancelled"
reason = "gusts of 30 knots or more"
elif 6 <= wind_knots < 25:
decision = "racing"
reason = "good racing wind"
else:
decision = "postponed"
reason = "too little wind" if wind_knots < 6 else "too much wind"
print(f"{decision} ({reason})")
On the calm morning, 4 knots, Ruth’s script prints postponed (too little wind). In this
lesson, you ported that range test to JavaScript, where a line that looks right can make the
wrong call.
- Your JavaScript port already had the old chain, with
decisionandreasondeclared withletabove it, and each branch in braces. You updated it the same way Ruth did, and the reason became a ternary, with the condition first. - The comparison signs are the same in both languages, so the range test looks like it carries
across as it’s written,
6 <= windKnots < 25. It runs with no error and no warning, but on the calm morning, the port postsracing (good racing wind), where Python postspostponed (too little wind). - JavaScript has no chained comparisons, so it reads the test left to right, one pair at a
time:
6 <= 4isfalse, and thatfalseis compared with25. - Less than compares numbers, so JavaScript converts the boolean:
falsebecomes0, andtruebecomes1.0 < 25istrue, so the test is true. - Python agrees with that step,
(6 <= wind_knots) < 25isTrue, since its booleans count as 0 and 1 too. But its chain compares the wind with each number, never a boolean with 25. - The first step only ever gives
falseortrue,0or1, and both are below 25, so the test is true for any wind. On the strong morning, 26 knots, Python postpones for too much wind, and the port races. - On the main morning, 14 knots, both race, so testing only that morning would miss the slip.
- The same reading applies to plain numbers: JavaScript prints
truefor1 < 5 < 3, because1 < 5istrue, andtruecounts as 1, which is less than 3. Python printsFalse, because 5 isn’t less than 3. It can go the other way, too:3 > 2 > 1isfalsein JavaScript andTruein Python. - Python’s chain is shorthand for two comparisons joined with
and:6 <= wind_knots and wind_knots < 25. JavaScript has no shorthand, so you write both comparisons in full and join them with&&, JavaScript’sand. The wind stays in the middle, between 6 and 25, so the test still reads as a range.