[Tutor] A question about None
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Aug 22 04:22:13 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
>
> The idea is that if "None" returned from the sensor then nothing will
> happen and the loop will continue until "None" is not returned. Can
> anyone see the error of my ways?
The logic semsoverly complex, why not something like:
while True:
value = distance_sensor.get_distance_cm()
if not value: continue # back to the while
if value > 20:
...
elif value < 20:
...
if value == 20:
????
That seems to express more clearly what you stated in the text.
--
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