Search code examples
pythonnested-loops

How can i make this condition work inside this while loop?


Have been trying to write some code that is supposed to read a string on a list and see if the string in question is present in a certain range, but the IF is just ignoring the WHILE loop entirely...

This is the full thing, i have no idea what is making this not work... Thanks in advance

ls = list()
qt = int(input('How many numbers you want to analize: '))
for c in range(1,qt+1):
    ls.append(input(f'Write the number you want to analize: '))

start = int(input('First digit: '))
end = int(input('Last digit: '))

i = 0
for c in range(start, end, 1):
    n = str(c)
    while i < len(ls):
        if ls[i] in n:
            print(n, end=' → ')
        i += 1 
print('Done')


Solution

  • The while loop is not beeing ignored. You have two main issues:

    1. you do not reset i everytime the outside for loop enters a new iteration and because of that the part of the list which had already been checked for the first number is not beeing checked again for the next number. Move the i = 0 into the for loop and it will work as expected.

    2. You are not including the last number when counting the range. If you want all numbers between two numbers to be checked you need to count up to end + 1.

    my_list = []
    quantity = int(input('How many numbers you want to analize: '))
    for _ in range(1,quantity + 1):
        my_list.append(input(f'Write the number you want to analize: '))
    
    start = int(input('Start: '))
    end = int(input('End: '))
    
    for number in range(start, end + 1, 1):
        i = 0
        converted_number = str(number)
        while i < len(my_list):
            if my_list[i] in converted_number:
                print(converted_number, end=' → ')
            i += 1 
    print('Done')
    

    Another issue you have in your code is that it is unreadable. You should always try to make your code is as easy to understand as possible. Never use single character variable names (apart from counting variables like i or maybe mathematical expressions like m*x + b but not! a*b*c if you are dealing with cuboids as the three sides are different, always use length, width and height in that case). I changed the single character variable names in your code to descriptive names to make it easier to understand.