python error returning a variable but it prints fine
<p>Trying to figure out this why I'm getting this error about not declaring a variable.</p>

<p>this works fine:</p>

<pre><code> 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) &gt; largestIP:
                                 largestIP = latestIP
 #       return largestIP
         print largestIP
</code></pre>

<p>In the list of number tags the largest # is 16 and it outputs :</p>

<pre><code>python botoGetTags.py 
16
</code></pre>

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

<pre><code>         return largestIP
 #       print largestIP
</code></pre>

<p>And call the function:</p>

<pre><code>         return largestIP
         #print largestIP

 findLargestIP()
 print largestIP
</code></pre>

<p>I get this error :</p>

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

<p>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</p>

<p>Thanks!</p>

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

<pre><code>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
</code></pre>

python function loops