循环并附加名称列表

时间:2013-12-23 13:53:41

标签: python for-loop python-3.x

我正在编写一个程序,一直要求用户输入名称,直到输入单词END, 此时它会打印出名单。

代码:

import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to enter names...")
time.sleep(0.5)
print("...once you have finished, enter END to print off your list")
names = []
for i in names:
    name = input("Please enter a name: ")
    if name == "END":
        print(names)
        sys.exit()
    names.append(name)

问题是程序在尝试执行for循环之前退出。

为什么会发生这种情况,我该如何解决?

3 个答案:

答案 0 :(得分:10)

这是因为变量names为空因此无法迭代

所以请改用while循环:

while True:
    name = input("Please enter a name: ")
    if name == "END":
        print(names)
        break   
    names.append(name)

注意:要退出循环,请使用break代替sys.exit()简单比复杂

更好

答案 1 :(得分:3)

获取名称列表:

Python 3 +

names = list(iter(lambda: input('Enter name (leave blank to finish): '), ''))

Python 2.7 +

names = list(iter(lambda: raw_input('Enter name (leave blank to finish): '), ''))

<强>用法:

>>> names = list(iter(lambda: input('Enter name (leave blank to finish): '), ''))
Enter name (leave blank to finish): bob
Enter name (leave blank to finish): cindy
Enter name (leave blank to finish): 
>>> names
['bob', 'cindy']

在您自己的代码中实施:

import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to enter names...")
time.sleep(0.5)
print("...once you have finished, enter END to print off your list")
print(list(iter(lambda: input('Enter name (END to finish): '), 'END')))

<强>演示:

>>> 
Welcome inbar...
This program, powered by Python, it will ask you to enter names...
...once you have finished, enter END to print off your list
Enter name (END to finish): abe
Enter name (END to finish): bob
Enter name (END to finish): END
['abe', 'bob']

答案 2 :(得分:2)

names是一个空列表。

names = []

因为它没有项目,所以迭代它没有效果。


>>> names = []
>>> for name in names:
...     print(name)
...
>>> names = ['tim', 'timmy']
>>> for name in names:
...     print(name)
...
tim
timmy
>>>