0
Whats the output
Running these code I cant understand the output. Could you explain it? def count(numbers): total=0 for x in numbers: if x < 20: total = total + 4 print (total) list = [0, 1, 4, 10, 30, 40, 17] count(list)
3 Answers
+ 1
The output should be 20. The function count() basically goes through each number in the list provided. If the number is less than 20, then 4 will be added to the variable total. Once it's done, the console will output the total. The iterations look like this:
Iteration 1: 0 is less than 20, so 4 is added to total. total = 4
Iteration 2: 1 is less than 20, so 4 is added to total. total = 8
Iteration 3: 4 is less than 20, so 4 is added to total. total = 12
Iteration 4: 10 is less than 20, so 4 is added to total. total = 16
Iteration 5: 30 is greater than 20, so nothing happens.
Iteration 6: 40 is greater than 20, so nothing happens.
Iteration 7: 17 is less than 20, so 4 is added to total. total = 20
+ 1
x = 0
0 < 20
total = total + 4 //4
x = 1
1 < 20
total = total + 4 //8
x = 4
4 < 20
total = total + 4 //12
x = 10
10 < 20
total = total + 4 //16
x = 30
30 < 20 returns false
x = 40
40 < 20 returns false
x = 17
17 < 20
total = total + 4 //20
output: 20
0
For every number in the list that is less than 20...4 is added to the total.