+ 1
Python loops
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)
5 Respostas
+ 3
There is no error in your code
actually the for loop in your code will always execute 1 time and then break because you wrote your condition like that
What kind of output are you expecting from the code?
+ 2
Your loop will set the 1st element of the list to smallest and then exits and prints the smallest. What are you trying to accomplish. Try removing the break statement or changing it to continue to see the differences.
+ 2
Owh, i thought there was an error... I didn't know there was no error because in one of my lessons, it asked me which line has error.. hhehe.. Thank you so much, Niththish and ChaoticDawg!
+ 1
If the goal is to find the smallest number in the supplied list, there is a logic error in the code. As Niththish points out, the loop will only execute once since smallest will always equal None on the first pass and therefore the break will terminate the loop based on the structure of the if statement in which it is contained.
It is only coincidence that smallest gets set to the smallest value because it happens to be in the first index position.
+ 1
I got it! I couldn't understand why "None" was put there! It meant a null value. Thanks to all!