Chenko
Chenko

Reputation: 35

Unresolved reference when using variable

I'm trying to join a variable from a function in a list, but it says the variable is an unresolved reference. I've had a look around and can't find any explanations that I can understand as to why this might be. The error is on the variable IP from the function. Can anyone help and explain in simple terms please?

def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    usersip = IP
    print(IP)
    return IP
get_ip()

list_to_join = [time, nameofhost, hostsname, message, clients_input, IP,] #Errors when I try to include the time_at_start variable
delimiter = '&&'
datajoined = delimiter.join(list_to_join)

Upvotes: 0

Views: 1029

Answers (1)

John Kugelman
John Kugelman

Reputation: 361849

IP is a local variable inside of get_ip(). You can't use it outside of the function; it doesn't exist there.

Assign get_ip()'s return value to a variable and use that variable. You could name that variable IP as well. But to be clear, it's a different variable. Let's use a different name to make that obvious:

ip = get_ip()
list_to_join = [time, nameofhost, hostsname, message, clients_input, ip]

Upvotes: 1

Related Questions