【问题标题】:problem with infinite loop in python listpython列表中的无限循环问题
【发布时间】:2019-09-02 00:39:41
【问题描述】:

正在研究 Sweigart 的“使用 Python 自动化无聊的东西”。他提供了以下简单列表程序的示例。我完全按照他的编码,但程序会产生一个无限循环。我错过了什么?

在使用此示例时尝试搜索具有相同结果的其他人。找不到任何东西。

catNames=[]
while True:
     print('Enter the name of cat ' + str(len(catNames) +1) + ' (Or enter nothing to stop.):')
     name=input()
     if name == '':
          break
     catNames = catNames + [name]
print('The cat names are:')
for name in CatNames:
     print('    ' + name)

结果应该是:

The cat names are:
   tommy
   spot
   paws
   etc.

相反,我得到了第一个打印命令的无限循环。

【问题讨论】:

标签: python-3.x list


【解决方案1】:

这里有一个小错字:

for name in CatNames:
     print('    ' + name)

CatNames 应该是 catNames(catNames 中的小写 c),然后才能正常工作。此外,循环将继续取名,直到您停止输入姓名。只需在不输入名称的情况下按 Enter 键,循环就会中断并显示输出。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 2017-05-30
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多