【问题标题】:Python 3.7 : Why is only the last item in a list printing?Python 3.7:为什么只打印列表中的最后一项?
【发布时间】:2020-07-30 04:29:28
【问题描述】:

我正在自学“Python Crash Course”第 2 版,但遇到了一个我无法解决的问题。我已经重读了这本书的前几部分,搜索了互联网并搜索了其他 SO 答案。

官方书籍答案使用字典,但我尝试使用列表。

程序应该请求输入,将输入添加到列表中并继续重复,直到被告知停止。当被告知停止时,应打印整个列表。

我遇到的问题是打印中只有列表中的最后一项。

与其给出答案,不如给我一个提示,以便我真正学习。

谢谢,

查德里克

active = True
while active == True:
    places = []
    place = input("\nIf you could visit one place in the world, where would you go? ")
    places.append(place)
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        print(places)
        active = False

【问题讨论】:

  • 只需将places = []移出while循环即可:)

标签: list while-loop python-3.7


【解决方案1】:

原因是因为每次迭代都将列表重置为空。

尝试以下方法:

active = True
places = []
while active == True:
    place = input("\nIf you could visit one place in the world, where would you go? ")
    places.append(place)
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        print(places)
        active = False

另外,由于active 是一个布尔值,你只需要while active:

所以:

active = True
places = []
while active:
    place = input("\nIf you could visit one place in the world, where would you go? ")
    places.append(place)
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        print(places)
        active = False

【讨论】:

  • 啊哈!哦当然。当我说“places = []”时,它会将列表设置为空白列表。由于它在循环内,每次循环运行时,列表都会重置为空白列表。将它放在循环之外会导致它仅在开始时被设置为空。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
相关资源
最近更新 更多