简体   繁体   中英

How can I break the while loop on Python?

I'm starting with Python. I can't make this else condition work. The while loop doesn't break.

Code:

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)

I can't make this else condition work.

Your indentation is wrong. That's the reason your code is not working for the else condition. Your code should be as follows -

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)

Also, if you are wondering why python didn't give error even though else: was after while: , you can refer - this and this .

By typing "break". For example:

while(True):
    if(condition):
        break
# This code is reachable

Changing new_item.lower to new_item.lower() should fix your issue.

  • new_item is of type str, new_item.lower() runs the lower() method on that string object and returns the result.

You have an error in your indentation here as @Abhishek mentioned. But the reason why your while loop is not breaking is because of the line of code where you do

if new_item.lower == 'start':

@Abhishek has also pointed this out in his code sample but I will elaborate a little more, Here new_item.lower is a function object but you are not running that function. To actually run the function you have to use

if new_item.lower() == 'start:

this converts the new_item string into all lower case as you are trying to do here. Just new_item.lower is just a pointer to the function. If you actually print out new_item.lower you can see that it shows something like <built-in method lower of str object at 0x7f5144522cb0> which is telling you that it is a function at the said memory location. So in your line you are comparing whether a function is equal to the string 'start' where what you actually want to do is to see whether the result of the function acting on new_line is equal to the string 'start' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM