0

I've got a variable, and it's being used in the condition of a while loop inside a function. I get an error upon running that function saying: local variable 'audioLength' referenced before assignment

song = input("Enter a song to play: ")
songFile = song + ".mp3"
mp3File = MP3(songFile)
audioLength = int(mp3File.info.length)

def play():
    pygame.mixer.music.load(song + ".mp3")
    pygame.mixer.music.play()
    while audioLength != 0:
        audioLength -= 1
        time.sleep(1)

I'm not sure why it thinks audioLength is a local variable, and how can I fix this?

martineau
  • 119,623
  • 25
  • 170
  • 301
dwib
  • 583
  • 4
  • 19
  • It is global, but you have to add the line "global audioLength" at the beginning of the function to access it. – Caleb H. Nov 20 '18 at 22:59
  • Thanks, I've done that but now it's saying: unsupported operand type(s) for -: 'Label' and 'int'. As if audioLength is a type 'Label' not an int even though i've made it an into outside the function – dwib Nov 20 '18 at 23:02
  • @Caleb: You only have to declare it as `global` in a function if its value is going to be changed there—the case here—although it doesn't hurt do so even when it's not required because having it will make what's going on a little more explicit. – martineau Nov 20 '18 at 23:06
  • It is being changed inside this function... – Caleb H. Nov 20 '18 at 23:07
  • 1
    @Caleb: I know. I was correcting your earlier comment about having to do it as though it was always required. – martineau Nov 20 '18 at 23:09
  • Ibrahim: It sounds like you may have a name conflict if you're now getting errors like that (about `Label`). Ask a new question and include the code and the error traceback (if you can't figure it out yourself). – martineau Nov 20 '18 at 23:11

0 Answers0