-2

This is my code:

from random import randint

ant1 = 1
ant2 = 2
ant3 = 3
ant4 = 4
cntNum = 0
no = 0
yes = 0

def antMove(antNum):
    randomNum = randint(0,3)
    if randomNum == antNum:
        yes += 1
    else:
        print("No")   

while cntNum < 20:
    antMove(ant1)
    antMove(ant2)
    antMove(ant3)
    antMove(ant4)
    cntNum = cntNum + 1

if cntNum == 20:
    print(yes)    
Tryph
  • 5,946
  • 28
  • 49
D.Kachler
  • 1
  • 1
  • 2
  • Which line causes the error? – GingerPlusPlus Oct 07 '16 at 07:27
  • sry, my bad: line 12 and 17 – D.Kachler Oct 07 '16 at 07:30
  • full error: Traceback (most recent call last): File "/Users/2020_dimitri_kachler/Desktop/Ant.py", line 17, in antMove(ant1) File "/Users/2020_dimitri_kachler/Desktop/Ant.py", line 12, in antMove yes += 1 UnboundLocalError: local variable 'yes' referenced before assignment >>> – D.Kachler Oct 07 '16 at 07:30

2 Answers2

3

The important part of the message is bold: UnboundLocalError: local variable 'yes' referenced before assignment.

In the following line, you are trying to update the value of the yes variable which does not exist in the local scope of the function:

yes += 1

I assume you wanted to update the global yes variable. In this case you have to declare the yesvariable as global in your function:

def antMove(antNum):
    global yes

But it is admitted that it is a bad pratice and you should find a nicer way to achieve what your want.

Tryph
  • 5,946
  • 28
  • 49
2

You got a scope issue here. Inside your script, yes apperas 2 times. 1 time as a global variable and 1 time as a — not existent - local one. Beside of the fact, that this is dangerous, you can solve your issue with something like

def antMove(antNum):
    global yes
    randomNum = randint(0,3)
    if randomNum == antNum:
        yes += 1
    else:
        print("No")

Do you see the global yes statement? This allows you to write the global variable yesinside context of the method.

In most cases I have seen this, global is a sign for either people coming from C or bad coding. If you reuse your little script it will be fun to debug a wrong increasing of yes.

frlan
  • 6,950
  • 3
  • 31
  • 72