简体   繁体   中英

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()
movie = str(input("Enter the name of a movie: ")) if movie == 0: break if movie:= 0. movies.append(movie)

The idea is correct here. But there is one mistake. You are asking for a string input then checking if the string input is an integer. Try to take a string input but compare it to another string.

if movie == "0":
    break

Suggested Code I changed your code your code up a bit too, much cleaner

def main():
   movies = []
   while "0" not in movies:
      movies.append(str(input("Enter the name of a movie: ")))
   print("That's your list")
   print(movies[:-1])
main()

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()
 movie = str(input("Enter the name of a movie: "))
 if movie == 0:
     break
 if movie != 0:
     movies.append(movie)

This seems good but remember you are comparing string value (movie) with an integer like:

if movie == 0:  #thats the mistake . now correct one is listed below

if movie == "o":
      break

Hope you understood this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM