Search code examples
pythonwhile-loopraw-input

How to break a loop when inputting unspecified raw_input?


I want to write an interface using a while loop and raw_input.

My code looks like this:

while True:
    n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit)
    if n.strip() == 'p':
        mp3.pause()
    if n.strip() == 'u':
        mp3.unpause()
    if n.strip() == 'p':
        mp3.play()
    if n.strip() == 's':
        mp3.stop()
    if n.strip() == 'q':
        break

But I want it to break if I input anything that isn't specified in the raw_input.

    if not raw_input:
        break

Returns and IndentationError: unindent does not match any outer indentation level.

        if not raw_input:
            break

Does not return any error but doesn't work as I want it to. As far as I know, it does nothing at all.

Also, if there's a cleaner way to write my loop, I love to hear it.


Solution

  • You are getting an indent error because you do not have a closing double quote.

    n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit")
    

    If you want to have the while look break if there is any other value then put all of your conditions into elif statements, and an all includisve else at the end. Also I just put lower and strip onto the end of the raw_input statement.

    while True:
        n = raw_input("'p' = pause, 'u' = unpause, 'pl' = play 's' = stop, 'q' = quit").strip().lower()
        if n == 'p':
            mp3.pause()
        elif n == 'u':
            mp3.unpause()
        elif n == 'pl':
            mp3.play()
        elif n == 's':
            mp3.stop()
        elif n == 'q':
            break
        else:
            break
    

    You could also put all of the valid answer options into a dictionary, but it looks like you should start with the simple solution to understand the flow. Also you used a p for both play and pause. You will want to use a unique value to differentiate so I added 'pl' for play.