chowpay
chowpay

Reputation: 1687

python error returning a variable but it prints fine

Trying to figure out this why I'm getting this error about not declaring a variable.

this works fine:

 def findLargestIP():
         for i in tagList:
                 #remove all the spacing in the tags
                 ec2Tags = i.strip()
                 #seperate any multiple tags
                 ec2SingleTag = ec2Tags.split(',')
                 #find the last octect of the ip address
                 fullIPTag = ec2SingleTag[1].split('.')
                 #remove the CIDR from ip to get the last octect
                 lastIPsTag = fullIPTag[3].split('/')
                 lastOctect = lastIPsTag[0]
                 ipList.append(lastOctect)
                 largestIP  = int(ipList[0])
                 for latestIP in ipList:
                         if int(latestIP) > largestIP:
                                 largestIP = latestIP
 #       return largestIP
         print largestIP

In the list of number tags the largest # is 16 and it outputs :

python botoGetTags.py 
16

But the above only printed out the variable I need to pass that on to another function but when I modify the code above

         return largestIP
 #       print largestIP

And call the function:

         return largestIP
         #print largestIP

 findLargestIP()
 print largestIP

I get this error :

python botoGetTags.py
Traceback (most recent call last):
  File "botoGetTags.py", line 43, in <module>
    print largestIP
NameError: name 'largestIP' is not defined

My guess is I have to initialize the variable in global.. But when I do that by making largestIP = 0, it returns 0 instead of the value that is in the function

Thanks!

Upvotes: 0

Views: 49

Answers (2)

Jivan
Jivan

Reputation: 23068

It's because largestIP only exists in the scope of your findLargestIP function.

Since this function returns a value but you simply call it without assigning to a new variable, this value gets "lost" afterwards.

You should try something like:

def findLargestIP():
    # ...
    return largestIP

myIP = findLargestIP() # myIP takes the value returned by the function
print myIP

Upvotes: 1

rlee827
rlee827

Reputation: 1873

When a function returns a value, it has to be assigned to a value to be kept. Variables defined inside a function (like b in the example below) only exist inside the function and cannot be used outside the function.

def test(a):
    b=a+1
    return b
test(2) # Returns 3 but nothing happens
print b # b was not defined outside function scope, so error
# Proper way is as follows
result=test(2) # Assigns the result of test (3) to result
print(result) # Prints the value of result

Upvotes: 4

Related Questions