Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading