Functions Lesson 4: Problem with Global variables? Exe 4.2

HI, doing the exercise 4.2 I got the solution with a function called leerlaser() which works fine and I tried a second solution by leerlaser2(). here the code:

from robot_control_class import RobotControl 

ob1 = RobotControl()

def leerlaser(val1, val2, val3):

    dist1 = ob1.get_laser_summit(val1)

    dist2 = ob1.get_laser_summit(val2)

    dist3 = ob1.get_laser_summit(val3)

    return [dist1, dist2, dist3]

def leerlaser2(vals):

    

    for i in vals:

        print (i)

        j=0

        dist[j]= ob1.get_laser_summit(vals[j])

        j=j+1    

    return dist

distancias = leerlaser(10, 100, 500)

print (distancias[0])

print (distancias[1])

print (distancias[2])

valores = (100, 300, 460)

distancias = leerlaser2(valores)

print (distancias[0])

print (distancias[1])

print (distancias[2])
------------------------------------
So when running the code, leealser() works and when executing leerlaser2() I got:

100
Traceback (most recent call last):
  File "function_2.py", line 33, in <module>
    distancias = leerlaser2(valores)
  File "function_2.py", line 17, in leerlaser2
    dist[j]= ob1.get_laser_summit(vals[j])
NameError: global name 'dist' is not defined

I tried defining dist as global but still not working… I do not know where the problem is.

Thanks.

Hi @david,

the reason why you are having this error is that you are referring to the dist variable on the leerlaser2 , but this variable is not defined inside that function.

You can solve this problem just by declaring the variable at the beginning of the function.

Something like:

dist = {}

This would declare a dictionary, which would allow you to set the values by index as you are trying (but in dictionaries, it is called key instead of index).

If you what you want is really a list instead of dictionary, you can define the dist variable with:

import numpy as np

dist = np.zeros(len(vals))

This would define a list called dist filled with zeros, and the list would have the length of the vals variable.

Please let us know should you need further assistance.

OK thanks. I thought that it was just enough : dist[j]= ob1.get_laser_summit(vals[j]) as declaration…

By the way if I used a dictionary like dist = {} then the command print (distancias [1] ) fails… Any tip here?

If you define dist = {} it is initially an empty dictionary. You first have to create the keys like:
dist[1] = 'whatever', only then you can access that value.