Skip to content
Advertisement

How can I exit a while loop after the user inputs “0”? If user inputs anything else, I want it to continue

Write a Python program that will ask the user for the name of a movie. Add the movie entered to a list. Continue asking for a movie until the user enters ‘0’. After all movies have been input, output the list of movies one movie per line.

This is what I’ve tried:

def main():
    movies = []
    while movies != 0:
        movie = str(input("Enter the name of a movie: "))
        if movie == 0:
            break
        if movie != 0:
            movies.append(movie)

    print("That's your list")
    print(movies)

main()

Advertisement

Answer

Use the break keyword to interrupt either a while or a for loop.

The code given by BuddyBob is not 100% correct because it will include the “0” in the list of movies (since it is first appended). The code given by ALI NAQI is actually comparing with a lowercase ‘o’.

I believe this would be the best way:

def main():
    movies = []
    while True:
        movie = input("Enter the name of a movie: ")
        if movie == "0":
            break
        else:
            movies.append(movie)

    print("That's your list")
    print(movies)

main()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement