在用户输入“0”后,如何退出while循环?如果用户输入任何其他内容,我希望它继续

fnvucqvd  于 2021-07-14  发布在  Java
关注(0)|答案(3)|浏览(405)

编写一个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()
vsikbqxv

vsikbqxv1#

使用 break 关键字中断 while 或者 for 循环。
buddybob给出的代码不是100%正确的,因为它将在电影列表中包含“0”(因为它是第一次附加的)。ali naqi给出的代码实际上与小写字母“o”比较。
我相信这是最好的方法:

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

efzxgjgh2#

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

oknrviil3#

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

这看起来不错,但请记住,您将字符串值(movie)与整数进行比较,例如:

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

if movie == "o":
      break

希望你能理解。

相关问题