Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何停止循环_Python_List_Loops_Input - Fatal编程技术网

Python 如何停止循环

Python 如何停止循环,python,list,loops,input,Python,List,Loops,Input,我写了这个代码,我正在努力让它工作。我试图做的是提示用户输入员工的姓名,并使用列表存储姓名 现在我遇到的问题是循环,当用户键入“done”时,循环将停止,然后显示输入的名称数,而对于另一个循环,则在其各自的行上显示输入的名称 我不知道我在代码中犯了什么错误,但在用户输入名称后,它会说:“按enter继续添加名称”,它还会说:“如果您想停止添加名称,请键入=完成” 如果用户点击enter,那么它应该询问另一个名称并重复这些问题,以查看用户是否希望添加更多或停止。但出于某种原因,即使用户按enter

我写了这个代码,我正在努力让它工作。我试图做的是提示用户输入员工的姓名,并使用列表存储姓名

现在我遇到的问题是循环,当用户键入“done”时,循环将停止,然后显示输入的名称数,而对于另一个循环,则在其各自的行上显示输入的名称

我不知道我在代码中犯了什么错误,但在用户输入名称后,它会说:“按enter继续添加名称”,它还会说:“如果您想停止添加名称,请键入=完成”

如果用户点击enter,那么它应该询问另一个名称并重复这些问题,以查看用户是否希望添加更多或停止。但出于某种原因,即使用户按enter键继续添加姓名,它仍会输出输入的姓名数和姓名列表。我不希望发生这种情况,我正试图让它显示结果,只有当用户键入“完成”,但“完成”一词不能显示在输出中时,它才会显示结果。我已经看了一遍又一遍代码,不知道我做错了什么

这是我的密码:

employee_list=[]

stop='done'

while stop == 'done':

    employee_name=input('Enter name of employee:')

    employee_list.append(employee_name)

    print('Press enter to continues adding names')

    enter_another=input('If you would like to stop adding names, type=done  ')

      print()

    list_size=len(employee_list)

    print('The number of employees you have entered: ', list_size)

    for index in range(list_size):
        print(employee_list[index])

如果有人键入done,您的代码中没有签入

例如:

if enter_another == "done":
    stop == "finished now"
但这是没有意义的,你的检查是说,如果停止了,然后继续,这在语义上是没有意义的

请尝试以下方法:

more_employees = True
while more_employees: # Never do thing == True
    # ... your code

    enter_another=input('If you would like to stop adding names, type=done  ')

    if enter_another == "done":
        more_employees = False

    # ... the rest of your code
  
如上所述:

不要使用==将布尔值与True或False进行比较

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

试试这个。我已经把你的打印条件排除在外了

employee_list=[]
stop='done'

while stop == 'done':
    employee_name=raw_input('Enter name of employee: ')

    employee_list.append(employee_name)

    print 'Press enter to continue adding names'

    enter_another=raw_input('If you would like to stop adding names, type=done  \n')

    if enter_another == 'done': 
        stop = 'random'

print 
list_size=len(employee_list)
print 'The number of employees you have entered: ', list_size

for index in range(list_size):
    print employee_list[index],

我试过了,但我一直得到的是:“如果你想停止添加姓名,那么每次我按enter键时,type=done都会重复。哎哟,那应该更糟糕了。”。试试看是否有用。谢谢你的帮助。尝试后,出现一个错误:如果enter_other==done:UnboundLocalError:local变量'enter_other'在分配之前被引用。您已将检查置于分配之前。再次感谢您的帮助,我非常感谢。遗憾的是,它仍然不起作用。