[Tutor] A question about None
dn
PyTutor at DancesWithMice.info
Sun Aug 22 04:25:42 EDT 2021
On 22/08/2021 19.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?
What if the distance is 20(cm)?
while True
measure = distance_sensor.get_distance_cm()
if measure is not None:
if measure > 20:
motor_pair.set_default_speed(20)
else:
motor_pair.set_default_speed(-20)
motor_pair.start()
Assuming:
- correct understanding of >, <, or =
- start() applies in either case and as long as the sensor returned a value
- consider adding a sleep() to the loop, depending upon the necessary
frequency of sensing
--
Regards,
=dn
More information about the Tutor
mailing list