Not sure why my python output is looping
<p>I wrote a little bit of code to read a number in a file. Append it to a variable, then increment the number so the next time it runs the number in the file will be number +1. It looks like its working except it seems to increment twice.. For example here is my code :</p>

<pre><code> 11 def mcIPNumber():
 12         with open('mcIPlatest.txt', 'r+') as file:
 13                 NameNumber= file.read().replace('\n','')
 14                 NameNumber=int(NameNumber)
 15                 NewNumber= NameNumber+1
 16                 print "newnumber = %s" % NewNumber
 17                 file.seek(0)
 18                 file.write(str(NewNumber))
 19                 file.truncate()
 20         return NameNumber
 21
 22 def makeNameMCTag():
 23         NameNumber = mcIPNumber()
 24         NameTag = "varName" + str(NameNumber)
 25         print "Name Tag: %s" % NameTag
 26         mcGroup = "varTagmc"
 27         #IPNumber = 1
 28         mcIP = "172.16.0.%s" % NameNumber
 29         print ( "Multicast Tag: %s, %s" % (mcGroup,mcIP))
 30
 31 
 32 mcIPNumber()
 33 makeNameMCTag()
</code></pre>

<p>But here is my output.. notice that "NewNumber" gets printed out twice.. for some reason"  </p>

<pre><code>newnumber = 2
newnumber = 3
Name Tag: varName2
Multicast Tag: varTagmc, 172.16.0.2
</code></pre>

<p>So it correctly made my varName2 and my IP 172.16.0.2 (incremented my initial number in the file by 1) but this means the 2nd time I run it.. I get this:</p>

<pre><code>newnumber = 4
newnumber = 5
Name Tag: varName
Multicast Tag: varTagmc, 172.16.0.4
</code></pre>

<p>My expected result is this:</p>

<pre><code>newnumber = 3
Name Tag: varName3
Multicast Tag: varTagmc, 172.16.0.3
</code></pre>

<p>Any idea why its looping?</p>

<p>Thanks!</p>

<p>(by the way if you're curious I'm trying to write some code which will eventually write the tf file for my TerraForm lab)</p>

<p>Because of this:</p>

<pre><code> def makeNameMCTag():
     NameNumber = mcIPNumber()
</code></pre>

<p>You are calling mcIPNumber from inside makeNameMCTag, so you don't excplicitly need to call that method in line 32.</p>

<p>Alternatively</p>

<pre><code>def make_name_mc_tag(name_number):
    NameTag = "varName" + str(name_number)
    print "Name Tag: %s" % NameTag
    ...

make_name_mc_tag(mcIPNumber())
</code></pre>

<p>here you are passing the required data as a parameter.</p>

python loops