r/learnpython • u/thecutefuriousmantis • Oct 07 '26
Rate my simple algorithm for autonomous bots
import time
import random
distance_front = 0
distance_back = 0
distance_left = 0
distance_right = 0
loop = 1
poop = 1
i = 0
def lidar():
global distance_front, distance_back, distance_left, distance_right
distance_front = random.randint(0, 100)
time.sleep(0.1)
distance_back = random.randint(0, 100)
time.sleep(0.1)
distance_left = random.randint(0, 100)
time.sleep(0.1)
distance_right = random.randint(0, 100)
time.sleep(0.1)
print("front:", distance_front, "back:", distance_back, "left:", distance_left, "right:", distance_right)
def algorithm():
if distance_front < 20:
print("obstacle in front : back - right")
if distance_back < 20:
print("obstacle in back : front - neutral")
if distance_left < 20:
print("obstacle in left : front - right")
if distance_right < 20:
print("obstacle in right : front - left")
i = 0
while True:
lidar()
algorithm()
0
Upvotes
2
2
2
u/zanfar Oct 07 '26
There is no context about what anything is supposed to do, and the method names are all too generic to infer.
Most negatively, no program should require global variables.
1
1
u/socal_nerdtastic Oct 07 '26
I would write it like this:
import random
def lidar():
distance_front = random.randint(0, 100)
time.sleep(0.1)
distance_back = random.randint(0, 100)
time.sleep(0.1)
distance_left = random.randint(0, 100)
time.sleep(0.1)
distance_right = random.randint(0, 100)
time.sleep(0.1)
print("front:", distance_front, "back:", distance_back, "left:", distance_left, "right:", distance_right)
return distance_front, distance_back, distance_left, distance_right
def algorithm():
distance_front, distance_back, distance_left, distance_right = lidar()
if distance_front < 20:
print("obstacle in front : back - right")
if distance_back < 20:
print("obstacle in back : front - neutral")
if distance_left < 20:
print("obstacle in left : front - right")
if distance_right < 20:
print("obstacle in right : front - left")
algorithm()Note that I removed the globals (almost always a bad idea to use globals) and that you don't need to pre-declare the variables in python.
7
u/danielroseman Oct 07 '26
You don't say what this is supposed to do. Why does a distance_front of less than 20 print a message about "front: back - right"?
The biggest problem here is all those global variables. There's no call for these here. And even less call for three variables you don't even use.