[Tutor] A question about None
Mark Lawrence
breamoreboy at gmail.com
Sun Aug 22 03:59:24 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
Tut tut not your actual code, 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?
>
I think that you're over complicating it. With your code the subsequent
calls to get_distance_cm could return None so the comparison would fail
anyway. How about:-
while True
:
distance = distance_sensor.get_distance_cm()
if distance is not None:
if distance > 20:
speed = 20
else:
speed = -20
motor_pair.set_default_speed(speed)
motor_pair.start()
break
There are other ways to structure the loop using flags but IMHO it's six
of one, half a dozen of the other.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list