[Tutor] A question about None
Peter Otten
__peter__ at web.de
Sun Aug 22 05:54:02 EDT 2021
On 22/08/2021 10:22, Alan Gauld via Tutor wrote:
> 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
That conflates "far enough away" with "already hit the obstacle" ;)
>
> if value > 20:
> ...
> elif value < 20:
> ...
> if value == 20:
> ????
>
> That seems to express more clearly what you stated in the text.
Phil, you should break even this small sequence of statements into
functions. Example:
while True:
if obstacle_ahead():
drive_backwards()
else:
drive_forward()
Here's a spoiler for
def obstacle_ahead():
dist = distance_sensor.get_distance_cm()
return dist is not None and dist < 20
The function returns True if you are less than 20 cm from an obstacle.
Suppose we're at 21 cm from an obstacle. No obstacle ahead, so we're
going forward, say two cm until the next measurement.
Now there is an obstacle, let's reverse gears and go backwards -- until
we're back at 21 or 22 cm when there is no more obstacle and we can go
forward again.
Effectively the vehicle oscillates around a distance of 20 cm of the
first obstacle it encounters. No fun to watch!
Therefore I recommend that you devise a more interesting strategy before
you resume coding. Giving the steps expressive names like in my example
should help you understand what will happen without even implementing
those steps.
More information about the Tutor
mailing list