Iterations Loop Idioms
Code Example 1
print ('before')
for thing in [1,2,3,4,5,6,7,8,9,0]:
print (thing)
print('after')
Output
before
1
2
3
4
5
6
7
8
9
0
after
Code Example 2
largest_so_far = -1
print ('Before',largest_so_far)
for the_num in [9,43,65,12,0,56,78,33,90,235,475,11287,5,9,0,1223]:
if the_num > largest_so_far:
largest_so_far = the_num
print(largest_so_far,the_num)
print ('After', largest_so_far)
Output
Before -1
9 9
43 43
65 65
65 12
65 0
65 56
78 78
78 33
90 90
235 235
475 475
11287 11287
11287 5
11287 9
11287 0
11287 1223
After 11287
We write the function that compare and keep the larger number if the current number in the_num is larger than largest_so_far it will keep the value of the_num as largest_so_far then it will check again and again if the current number is larger than before it will forget the last number and keep ther larger instead
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("Sma6llest:", smallest)Output
Before: None Smallest: 3 -
Ans
6