【问题标题】:how to stop a loop如何停止循环
【发布时间】:2014-09-22 01:50:49
【问题描述】:

我编写了这段代码,试图让它工作。我要做的是提示用户输入员工姓名并使用列表来存储姓名。

现在我遇到问题的部分是循环,当用户键入“完成”时,假设循环停止,然后显示输入的名称数量,并在另一个循环中显示每个输入的名称在自己的线上。

我不知道我在代码中做错了什么,但是,在用户输入名称后,它会说:'按 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])

【问题讨论】:

    标签: python list loops input


    【解决方案1】:

    如果有人键入 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
      
    

    如上所述,PEP8 recommends against comparing thing == True

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

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

    【讨论】:

    • 我试过了,但我一直得到的是:'如果你想停止添加名字,type=done 每次我按回车键都会重复。
    • 哎呀,应该是more_employees = False。试试看是否有帮助。
    • 感谢您的帮助。试了一下,报错:if enter_another == "done": UnboundLocalError: local variable 'enter_another' referenced before assignment
    • 你已经把检查放在了作业之前。
    • 再次感谢您的帮助,我真的很感激。可悲的是仍然无法正常工作。
    【解决方案2】:

    试试这个。我已将您的打印条件置于循环之外。

    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],
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2022-01-11
      • 2014-05-30
      • 2010-09-26
      • 2012-06-19
      • 2019-07-01
      • 2013-09-11
      • 2012-11-29
      • 2012-01-16
      相关资源
      最近更新 更多