Iterations: Loop Idioms

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)

In the course where does the error come and why?

This was the question in the Python for everybody(Scientific computing with python):

Q)Below is code to find the smallest value from a list of values. One line has an error that will cause the code to not work as expected. Which line is it?:

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)

My doubt is which line would cause and error and what would it cause the code to not work?

try it, paste your code here: http://pythontutor.com/visualize.html#mode=display
use the “visualize execution” button, and see what happens

the code will always say that the first item is the smallest, you can try with different lists

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