1

I get the error

How often? 33
Traceback (most recent call last):
  File "main.py", line 20, in <module>
    main()
  File "main.py", line 17, in main
    won += 1
UnboundLocalError: local variable 'won' referenced before assignment

when I try to run the following code:

teller = 0
throw = int(input('How often?'))
won = 0 
    def main():
        pricedoor = round (3 * np.random.rand() + 0.5)
        if pricedoor == 4 : pricedoor = 3
        choicedoor = round (3 * np.random.rand() + 0.5)
        if choicedoor == 4 : choicedoor = 3
        sheepdoor = mf.quizmasteropens(pricedoor, choicedoor)
        #choicedoor = choicedoor

        if choicedoor == pricedoor:   
          won += 1

    while teller < throw :
        main()
        teller = teller + 1

How can I fix this problem? Thanks in advance for the help!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

2 Answers2

1

To make this work, you need to move the assignment to won inside main():

def main():
   won = 0 
   ...

If you want to make the value of won available outside main(), I'd suggest returning it from the function like so:

def main():
   won = 0 
   ...
   return won

If you do this, the caller would be able to assign the value to its own variable (which may or may not be called won - that's up to you):

won = main()
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Scope of variable won is not defined for main(). If you want to use won you need to defined as :

def main():
    won = 0
Pushplata
  • 552
  • 4
  • 10