Home > Mobile >  Using A variable to Index
Using A variable to Index

Time:11-02

My current problem is I want to search for items in a list but only for the number of items in said list

  b = len(drumsound)
  a = 0
  while b > 0:
   if drumsound[a] == "1":
    mixer.music.load("soundfiles/snare.mp3")
    mixer.music.set_volume(1)
    mixer.music.play()
    b-1
    a  = 1
   
   elif drumsound[a] == "2":
     mixer.music.load("soundfiles/tom.mp3")
     mixer.music.set_volume(1)
     mixer.music.play()
     b-1
     a  = 1

I would like to know if there is any way for me to be able to make this work

CodePudding user response:

Your problem may be the substraction that you are doing to the b variable in both conditions:

b = len(drumsound)
  a = 0
  while b > 0:
   if drumsound[a] == "1":
    mixer.music.load("soundfiles/snare.mp3")
    mixer.music.set_volume(1)
    mixer.music.play()
    b -= 1
    a  = 1
   
   elif drumsound[a] == "2":
     mixer.music.load("soundfiles/tom.mp3")
     mixer.music.set_volume(1)
     mixer.music.play()
     b -= 1
     a  = 1

CodePudding user response:

The problem with your code was addressed by @U12-Forward in the comments. I just want to show how you can do the same in more pythonic way

drumsounds = '122112'
files = {'1':"soundfiles/snare.mp3", '2':"soundfiles/tom.mp3"}
for tone in drumsounds:
    mixer.music.load(files[tone])
    mixer.music.set_volume(1)
    mixer.music.play()
  • Related