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)
Iâve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the âpreformatted textâ tool in the editor (</>) to add backticks around text.
Can you please reply me with a video on how to display the code in the forum with any example of a code i didnât understand, please help me with this
Your code just looks at the first item of the list (which is 3) and puts that into the smallest variable. It works like this: For each item (itervar) in the given list ([3, 41, 12, 2, 74, 15]) you check if the preset variable âsmallestâ is bigger than the current item (first item is 3 in this list). However, since the if statement is True in the first iteration (smallest is None), you set that smallest variable to the itervar (3 in this case) and then you put a âbreakâ immediately after it. That causes you to break out of the whole for loop, essentially stopping it right after the first iteration (it only checked 3 here) and then going on with the next line of code which is not included in the for loop (which is the last line of code here, print(âSmallest:â, smallest). If you donât put the break statement inside, the for loop will go through each item until the last one and then âbreak out of the loopâ on its own so to say. That is why itâs called a definite loop, since it has a set number of times (in this case the length of the list) it iterates through a given iterable. If you put "print(âdebugâ) right before you set smallest = itervar, you can observe that the loop only executes one single time. Print statements are really helpful for cases where you donât understand whatâs going on. I hope I could help you!