Python loops | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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)

17th Sep 2021, 7:33 AM
Adam Haller
Adam Haller - avatar
5 Réponses
+ 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?
17th Sep 2021, 7:37 AM
Niththish
Niththish - avatar
+ 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.
17th Sep 2021, 7:38 AM
ChaoticDawg
ChaoticDawg - avatar
+ 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!
17th Sep 2021, 7:54 AM
Adam Haller
Adam Haller - avatar
+ 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.
17th Sep 2021, 9:59 AM
Paul K Sadler
Paul K Sadler - avatar
+ 1
I got it! I couldn't understand why "None" was put there! It meant a null value. Thanks to all!
18th Sep 2021, 7:12 AM
Adam Haller
Adam Haller - avatar