How do I modify certain things

Hi, it’s me again. I’ve been stuck on this one for a few days and need some help. Here’s a dumbed down version of the code:

def music1
	backgroundMusic = loader.loadSfx("phase_3/audio/bgm/tt_theme.ogg")
	backgroundMusic.setLoop(True)
	backgroundMusic.setVolume(0.25)
	backgroundMusic.play()
	
def music2
	backgroundMusic = loader.loadSfx("phase_3/audio/bgm/create_a_toon.ogg")
	backgroundMusic.setLoop(True)
	backgroundMusic.setVolume(0.25)
	backgroundMusic.play()

Basically, I want to stop playing music1’s music when I switch to music2. I can’t work out how to modify things inside of a defined command, which I what I really need to do.

Essentially, you want access to the objects created within those methods (the ones that you’re naming “backgroundMusic”). However, since they aren’t associated with any external object, you’re losing access to them as soon as the method in which they’re defined ends.

If I may ask, are you familiar with the term “scope” in the context of programming? If not, I recommend that you read up on it. Next, are familiar with object-oriented programming? I think that it might be rather useful to you in structuring your programs.

(You could also use global objects, which is a simpler approach–to start with. It can lead to things getting rather messy and difficult to work with later on, I feel. Finally, you could return the objects from their methods and pass them from method to method, keeping a reference to them that way, but that can become quite a nuisance, I’ve found.)