Python for loops error

hello, can i know the error in the block of code below?

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)

what do you think is the error? try following the code flow, or try to run it and see what it prints

what should be the result? what does it print?

you can also use a tool like this to see the execution of the code
https://pythontutor.com/visualize.html#mode=edit

1 Like

Line no.6
Try without “break”.

1 Like

I tried removing the break…

I got

Before: None
Loop: 3 3
Loop: 41 3
Loop: 12 3
Loop: 9 3
Loop: 74 3
Loop: 15 3
Smallest: 3

Is this the debugged one?

It should print out the smallest but i really don’t know the error hehe…

I got this in the compiler…

Before: None
Smallest: 3

Solved! Thanks for helping to those who replied! I didnt’t understand the fx of None there, i was wondering why None was compared to an integer. But I did not know why line 6 has error.

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

You need to push the indent back of the print of loop. That is the only error. everything else is fine. If you don’t push it back, you will never get that line printed at any time. I hope you understood. You can get back to me, if you don’t understand.

1 Like

Thank you so much for looking here! But the answer says the error is on line 6, why is it so?

I don’t think that you need to push the indent of the print back. That print is intended to show what happens inside of the loop.

@davidbrashear112 do you know what the break keyword does? It looks like this code is finding the smallest value in an array. How could a break keyword prevent this from happening?

1 Like

Yes, the break should be removed and let the print loop stay as it is. It is an error in the break because it breaks the loop with the first element itself and doesn’t go through the other numbers in the list, I stand corrected.

1 Like

Yes you are right @JeremyLT . No need to push the indent of the print back. The error is in the break keyword which stops it looping in the very first number it checks.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.