hayful59
hayful59

Reputation: 17

Breaking a loop

Hello im trying to make an mp3 player. At the moment Im just trying to get it to print the found mp3 file to the console but its stuck in an infinate loop and Im not sure how to break it as im still new to python

def mp3_finder():
    times_done = 5
    starting = 0
    for file in os.listdir(full_dir):
        if file.endswith(".mp3"):
            while starting < times_done:
                starting = starting + 1
                print(file)

    return mp3_finder()

EDIT:

Sorry i wasnt very clear but what im trying to do is find the mp3 file and print the name to the console 5 times but because it keeps finding the file it keeps printing it to the console until python stops it because it printed hundreds of it

Upvotes: 0

Views: 66

Answers (3)

skyking
skyking

Reputation: 14400

First of all you should probably not call mp3_finder at the end of the function - it will recurse infinitly. Also you probably don't want the inner loop, it wil just print the first file five times. Combined the result will be that the function prints the first file five times, then it calls itself which again prints the first file five times and so on until you reach maximum recursion depth.

What you want to return isn't clear maybe it's OK to just return None (ie skip the return statement entirely). Second you'll need to break out of the loop when you're done.

def mp3_finder():
    times_done = 5
    starting = 0
    for file in os.listdir(full_dir):
        if file.endswith(".mp3"):
            if starting < times_done:
                starting = starting + 1
                print(file)
            else:
                break

Upvotes: 0

FirebladeDan
FirebladeDan

Reputation: 1069

def mp3_finder():
   times_done = 5
   starting = 0
   for file in os.listdir(full_dir):
     if file.endswith(".mp3"):
        while starting < times_done:
            starting = starting + 1
            print(file)

mp3_finder()

Watch your indent otherwise looks good

Upvotes: -1

Cyphase
Cyphase

Reputation: 12002

You're calling the function again in the return statement; since you're printing within the function, you can just remove the return entirely.

def mp3_finder():
    times_done = 5
    starting = 0
    for file in os.listdir(full_dir):
        if file.endswith(".mp3"):
            while starting < times_done:
                starting = starting + 1
                print(file)

That answers your question about breaking a loop, but perhaps you should ask another one about your code, because I don't think it's going to give you the output you want.

Upvotes: 2

Related Questions