I am new to python and I am going through the free course on python for everybody. In the course they gave us a question:
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)
The answer is line 6. I am confused as to why line 3 isn't the answer? smallest = None, but None is a string. Wouldn't the code break because 3 < None would not work? (in the itervar<smallest) part.
Many thanks!
CodePudding user response:
None
isn't a string. It's a special value that signifies a lack of a meaningful value.
But you're right that you can't compare strings and integers or None
with an integer.
That never happens, though, because or
short-circuits: if you have A or B
and A
is true, then B
never gets evaluated. So if smallest is None
then it doesn't compare it to itervar
, and it's all good.
CodePudding user response:
None isn't a string, it is a python keyword that refers to no value None in Python
And no, it wouldn't break.
This is because the 1st condition is checked first. And if smallest=None
, since it is an or
block, the second condition doesn't get checked and hence the loop works.
The condition itervar < smallest
will be checked only if the 1st condition is False
CodePudding user response:
"None" isn't a string. It specifies that "smallest" currently has no value, similar to being empty. The first part of the if condition (small is None) is true only once in the first iteration. It then sets "smallest" to "itervar" (3, which in this case is the first number in the list), after this the loop immedietly stops due to the "break" statement, and moves to the 8th line where it prints "Smallest: 3". So the break statement was the problem, which makes the answer line 6.