如何在Python上中断while循环?

如何在Python上中断while循环?,python,Python,我从Python开始。 我不能让这个否则条件起作用。while循环不会中断 代码: list = [] uniques = [] start = False while start: new_item = input('Add item: ') list.append(new_item) if new_item.lower == 'start': start = True else: for number in list: if

我从Python开始。 我不能让这个
否则
条件起作用。while循环不会中断

代码:

list = []
uniques = []
start = False

while start:
    new_item = input('Add item: ')
    list.append(new_item)
    if new_item.lower == 'start':
        start = True
else:
    for number in list:
        if number not in uniques:
            uniques.append(number)
uniques.sort()
print(uniques)
通过键入“break”。 例如:

while(True):
    if(condition):
        break
# This code is reachable
我不能让这个条件起作用

你的缩进是错的。这就是代码不适用于else条件的原因。您的代码应该如下所示-

list = []
uniques = []
start = True                          # In your question you have mentioned it as False here. 
                                      # It should be True for your loop to start.

while start:
    new_item = input('Add item: ')
    list.append(new_item)
    if new_item.lower() == 'start':   # You probably meant .lower() here and not .lower
        start = False
    else:                             # Properly indented this else statement
        for number in list:
            if number not in uniques:
                uniques.append(number)
uniques.sort()
print(uniques)

另外,如果您想知道为什么python没有给出错误,即使
else:
while:
之后,您可以参考-和。

将new\u item.lower更改为new\u item.lower()应该可以解决您的问题

  • new_item的类型为str,new_item.lower()对该字符串对象运行lower()方法并返回结果

    • 您在此处的缩进中有一个错误,如@Abhishek所述。但是while循环之所以没有中断,是因为您所使用的代码行

      if new_item.lower == 'start':
      
      @阿披舍克在他的代码示例中也指出了这一点,但我将进一步阐述 ,此处new_item.lower是一个函数对象,但您没有运行该函数。要实际运行该函数,您必须使用

      if new_item.lower() == 'start:
      

      这会将
      new_项
      字符串转换为所有小写字母,就像您在这里尝试的那样。只是
      new\u项。lower
      只是指向函数的指针。如果您实际打印出
      new\u item.lower
      ,您可以看到它显示类似
      的内容,告诉您它是位于所述内存位置的函数。因此,在您的行中,您正在比较一个函数是否等于字符串
      'start'
      ,您实际想要做的是查看作用于新行的函数的结果是否等于字符串
      'start'

      ,您应该能够在
      start=False
      之后的行中添加一个
      break
      否则:
      需要正确缩进。