Question regarding Loop

Hello all,
While going through Python course, I came across a question that asked us to find out why this particular code that I have pasted down will cause an error. I ran this code and yet I could find no error . My code ran fine and showed me the output: smallest- 3.
If anyone has more insight on this, please feel free to shoot your thoughts and it would be helpful to me !

Thanks,
Regards!

smallest = None
print("Before:", smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
    if smallest is None or itervar < smallest:
        smallest = itervar
        break
    print("Loop:", itervar, smallest)
print("Smallest:", smallest)

That itervar < smallest is going to cause an error in a Python console since smallest is a NoneType and itervar is an integer value. The thing is here it doesn’t cause an error, but this is just wrong.

Hello!

First, welcome to the forum :partying_face:! We hope you learn a lot :slight_smile:.

In regards to the problem,

That’s because, in this specific case, the smallest value happens to be at the first position. The algorithm is wrong though because what happens if there’s a smaller value after the first small one?

Try it yourself, change the array to: [3, 41, 12, 9, 1, 74, 15].

1 Like

Yeah I didn’t notice this, the loop breaks after just one iteration.

1 Like

Got it! The break would reject an alternate case!

And yes I am enjoying the forum.
Thank you for establishing it!

1 Like