首页 > 解决方案 > 用户输入“0”后如何退出while循环?如果用户输入其他任何内容,我希望它继续

问题描述

编写一个 Python 程序,询问用户电影的名称。将输入的电影添加到列表中。继续询问电影,直到用户输入“0”。输入所有电影后,每行输出一部电影的电影列表。

这是我尝试过的:

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()

标签: pythonwhile-loop

解决方案


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

这个想法在这里是正确的。但是有一个错误。您要求输入字符串,然后检查字符串输入是否为整数。尝试接受一个字符串输入,但将其与另一个字符串进行比较。

if movie == "0":
    break

建议的代码 我也把你的代码改了一点,更干净

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()

推荐阅读