Search code examples
arrayslistloops

my loop stops comparing after a certain index


I have problem with my code specifically the for loop, where i search for the smallest and largest number in my list. It stops comparing a[i] with the current smallest or largest number at some point. I tried it with the input 23,34,68,3,566,2,1

 largest = None
    smallest = None
    a = []
    while True:
        num = input("Enter a number: ")
        if num == "done":
            break
        try:
            FailureCond = int(num)
        except ValueError:
            print("that's not a number")
            continue
        a.append(num)
        continue

    for i in range(len(a)):

        if smallest is None:
            smallest = a[i]
            largest = a[i]

        if a[i] < smallest:
            smallest = a[i]

        if a[i] > largest:
            largest = a[i]


    print("current list >",a)
    print("the smallest number is >",smallest)
    print("largest number is >",largest)

the output is

current list > ['23', '34', '68', '3', '566', '2', '1']
the smallest number is > 1
largest number is > 68

i tried printing every step of the loop, but i can't seem to find the mistake


Solution

  • After reviewing your code, I found the error that makes your code break in "weird" circumstances. It is the while loop where you input your numbers; if you look closely at the docs for the input function, you can see that the returned value gets transformed into a string, meaning that all of the following arithmetic operations seemed to be okay up to a certain point, however, in reality, the operations don't make sense. I fixed the part that is problematic in the following code snippet:

    while True:
        num = input("Enter a number: ")
        if num == "done":
            break
        try:
            FailureCond = int(num)
        except ValueError:
            print("that's not a number")
            continue
        a.append(int(num)) # This line was fixed
        continue