0

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)
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
Lucas Melo
  • 11
  • 3

4 Answers4

1

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 .

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
0

By typing "break". For example:

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

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.
user391
  • 105
  • 1
  • 12
0

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'.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Merlin11
  • 35
  • 5