[Tutor] A question about None

Alan Gauld alan.gauld at yahoo.co.uk
Sun Aug 22 07:51:17 EDT 2021


On 22/08/2021 08:25, Phil wrote:
> The distance sensor outputs "None" if the distance is greater than can 
> be measured and "None", of course cannot be compared. So I came up with 
> the following which is not quite correct:
> 
> while True
>      if distance_sensor.get_distance_cm() is not None:
>          if distance_sensor.get_distance_cm() > 20:
>              motor_pair.set_default_speed(20)
>              motor_pair.start()
>          else:
>              continue
> 
>      elif distance_sensor.get_distance_cm() is not None:
>          if distance_sensor.get_distance_cm() < 20:
>              motor_pair.set_default_speed(-20)
>              motor_pair.start()
>          else:
>              continue

Thee is another problem with the code above that nobody has pointed out
yet (although all the alternatives avoid it).

When reading from a dynamic data source such as a sensor it is very
important to process all possible values at the same time - ie.
before reading the sensor again. To illustrate why, consider
what happens if the sensor alternates between None and a value >20.

In the code above the first if test fails so no action is taken for
the None result, that's OK. But then, in the elif clause, we take
a second reading which is >20. Then in the if clause we take a
third reading which will be None so no action gets taken. But what
about the reading >20? It has been ignored....

That's another reason to read the value into a variable then
use that fixed value for all tests.

It may seem an unlikely or arcane condition but these things
happen very often when you start interacting with the real
world.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list