将用户输入附加到循环中的列表

时间:2017-08-31 07:37:19

标签: python list loops

我是python编程的新手,我正在做一些实验。希望我的问题不是太愚蠢:我正在编写一个小程序,它将输入添加到列表中,并在输入等于4时使用while循环打印它。问题是它永远不会停止添加输入并打印列表。 我的代码是:

S=input()
L=[]
while S!=4:
    L.append(S)
    if S==4:
        break
print(L)

4 个答案:

答案 0 :(得分:1)

问题是因为你有一次读取输入S,之后S总是1 while永远不会是4而你的循环永远不会弯腰,你必须添加你的输入list = [] number = -1 while number != 4: number = int(input()) list.append(number) print(list)

while

如果您在t need中检查S!= 4,那么statement in import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'mysql-python', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', 'pyramid_tm', 'simplejson', 'webtest', 'mock', 'pyopenms' ] setup(name='mypackage', version='0.1', description='mypackage', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web wsgi bfg pylons pyramid', packages=find_packages(), include_package_data=True, zip_safe=False, test_suite='mypackage_test', install_requires=[], entry_points="""\ [paste.app_factory] main = mypackage:main [console_scripts] initialize_mypackage_db = mypackage.scripts.initializedb:main """, ) creating /usr/local/lib/python2.7/dist-packages/mypackage-0.1-py2.7.egg Extracting mypackage-0.1-py2.7.egg to /usr/local/lib/python2.7/dist-packages Removing mypackage 0.1 from easy-install.pth file Adding mypackage 0.1 to easy-install.pth file Installing initialize_mypackage_db script to /usr/local/bin Installed /usr/local/lib/python2.7/dist-packages/mypackage-0.1-py2.7.egg Processing dependencies for mypackage==0.1 Searching for MySQLdb Reading https://pypi.python.org/simple/MySQLdb/ No local packages or working download links found for MySQLdb error: Could not find suitable distribution for Requirement.parse('MySQLdb')

答案 1 :(得分:1)

input()函数返回字符串对象,因此它们永远不能等于4,这是一个int对象。

要解决问题,请将4替换为'4'

这会将'4'视为字符串,因为当您输入4作为输入时,相等性将保持

答案 2 :(得分:1)

您的代码还有另一个大问题,您不再更新S,更正确的答案是:

S=input()
L=[]
while S!=4:
    L.append(S)
    if S=="4":
        break
    S = input()
print(L)

如果您不希望所有内容都阻止等待新输入,那么您可能会考虑引入线程,但如果仅允许用户向数组添加值并通过添加4来停止这样做可能有帮助

答案 3 :(得分:-1)

您在代码中创建了一个无限循环。进入循环后,您不会更改S的值。您应该添加从循环内部获取另一个输入,如下所示:

S=input()
L=[]
while S!=4:
   L.append(S)
   S = input()
print(L)

另外,代码中的if条件没用,因为它已经在while循环声明中设置了