@mrrouge
ok if i got you right you want the function to return a value — in your case the height of the legs. this value could then be used in a while loop. while loops are quite helpful but might run forever if done incorrect. I adapted the code a bit so the legs function returns the length of the legs which is then added to the y value in the while loop. There is a check inside the while loop so it will run for a maximum of 3000 times.
# -------------
#  settings 
pw = ph = 500
amount_x = 10
cell_w = pw / amount_x
max_h  = 50
gap = max_h * .2
# -------------
#  fucntion(s)
def legs(pos, max_w, max_h):
    x, y = pos
    length = random() * max_h
    step_s = random() * max_w
    polygon((x - step_s, y) , (x, y + length), (x + step_s, y), close = False)
    
    return length
# -------------
#  drawings
newPage(pw, ph) 
fill(None)
stroke(0)
strokeWidth(2)
for x in range(amount_x):
    
    count = 0
    y = -random() * max_h
    while y < ph:
        y += legs((x * cell_w + cell_w/2, y), cell_w/2, max_h)
        y += gap
        count += 1
        
        if count > 3000: break 
and the while loop without the check:
for x in range(amount_x):
    y = -random() * max_h
    while y < ph:
        y += legs((x * cell_w + cell_w/2, y), cell_w/2, max_h)
        y += gap