Practice question

Steven D'Aprano steve at pearwood.info
Tue Oct 7 10:48:55 CEST 2014


On Sun, 05 Oct 2014 20:18:13 -0400, Seymore4Head wrote:

> I think I get it now.  You are using a sample of answers.  So you could
> actually just run through them all.  (I haven't tried this yet)
> 
> for x in range(lo,hi)
>      print((15 <= x < 30) == (15<= x and x <30))

Yes, except using print is probably not the best idea, since you might 
have dozens of True True True True ... printed, one per line, and if you 
blink the odd False might have scrolled off screen before you notice.

With two numbers, 15 and 30, all you really need is five test cases:

- a number lower than the smaller of the two numbers (say, 7);
- a number equal to the smaller of the two numbers (that is, 15);
- a number between the two numbers (say, 21);
- a number equal to the larger of the two numbers (that is, 30);
- a number higher than the larger of the two numbers (say, 999);


The exact numbers don't matter, so long as you test all five cases. And 
rather than printing True True True... let's use assert instead:


for x in (7, 15, 21, 30, 999):
    assert (15 <= x < 30) == (15<= x and x <30)


If the two cases are equal, assert will do nothing. But if they are 
unequal, assert will raise an exception and stop, and you know that the 
two cases are not equivalent and can go on to the next possibility.


-- 
Steven



More information about the Python-list mailing list