python - 用户输入“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()
解决方案
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()
推荐阅读
- java - 如何使用 WebView 从 Google Drive 下载 PDF 文件
- sql - 使用数据框和 dbSendQuery 更新表
- sql - SQL - 遍历具有相同架构的本地表列表
- haskell - Haskell 中的类型 `Fix` 和函数 `fix` 是如何相同的?
- c++ - C++ 如何使用子类制作 unordered_map
- javascript - 计算(长度*数量=总(米),总(米)*价格=总价)但总价不会显示结果
- selenium - 运行 selenium 时出错,chrome 位置和 chrome 驱动程序问题
- ruby-on-rails - Ruby on Rails - 开发和生产的文件路径不同?
- c# - 基于两列聚合两个相同的列表并对第三列求和
- amazon-cognito - Cognito 创建导入作业 - 权限不足