[Tutor] A question about None
dn
PyTutor at DancesWithMice.info
Sun Aug 22 04:39:48 EDT 2021
On 22/08/2021 20.25, dn via Tutor wrote:
> 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()
>
> 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
Further thoughts:-
1 improve documentation, and
2 remove 'magic values' which are embedded/hidden within the code
forwards = 1
backwards = -1
speed = 20
significant_distance = 20
...
while True
measure = distance_sensor.get_distance_cm()
if measure is not None:
if measure > significant_distance:
direction = forwards
else:
direction = backwards
motor_pair.set_default_speed( speed * forwards )
motor_pair.start()
Am wondering why 'speed' is not an argument to start()?
The if-condition needs closer analysis, and could be compressed into a
single-line (if meaning remains clear)
Also, could replace the outer if-construct with a try-except.
Ultimately, this might give you the opportunity to count the number of
consecutive zero-responses from the sensor, in order to take appropriate
action.
--
Regards,
=dn
More information about the Tutor
mailing list