-5

Ive come across an error which i have tried tackling for a while now.

        if outerball.pos.x >= (self.r - 0.1):
            if self.rotations == 0:
                stopt = time.time ( )
                onerot = stopt - startt
                print(onerot)
            self.rotations += 1

        # update variable outputs
        timey.text = "time: %1.f" % onerot + " seconds"

error is timey.text = "time: %1.f" % onerot + " seconds" UnboundLocalError: local variable 'onerot' referenced before assignment

Ive tried globalizing the variable but it still hasnt made a difference. Can someone pls explain how i can fix this.

Thanks

  • 1
    `onerot` only assigned with value when it fits the `if condition` – Haifeng Zhang Feb 21 '17 at 23:06
  • 1
    Ask yourself this: What is the value of `onerot` when your `if` blocks don't execute? – jmoerdyk Feb 21 '17 at 23:07
  • I'm going to point you to [this question](http://stackoverflow.com/questions/15367760/unboundlocalerror-local-variable-referenced-before-assignment-when-reading-from) which suffers from the same issue as you: you have a variable that is conditionally defined. – Tadhg McDonald-Jensen Feb 21 '17 at 23:29

1 Answers1

1

In your case onerot is assigned a value only when it meets the nested if condition, you need to assign a default value to it

onerot = 0  # ---> assign a value to onerot here
if ....:
    if ...:
      //your code
timey.text = "time: %1.f" % onerot + " seconds"
Haifeng Zhang
  • 27,283
  • 17
  • 68
  • 115