Question 14
What is the output of the following code? [3 marks]
Solution
Initialize variables num with integer value 1932102, and total with integer value 0.
num |
num != 0? |
digit: num%10 |
New num: num//=10 |
digit >= 5? |
int(digit) % 2 != 0? |
New total |
|---|---|---|---|---|---|---|
1932102 |
True |
1932102 % 10 = 2 |
1932102 // 10 = 193210 |
2 >= 5: False |
2 % 2 = 0: False |
0 + 2 = 2 |
193210 |
True |
193210 % 10 = 0 |
193210 // 10 = 19321 |
0 >= 5: False |
0 % 2 = 0: False |
2 + 0 = 2 |
19321 |
True |
19321 % 10 = 1 |
19321 // 10 = 1932 |
1 >= 5: False |
1 % 2 = 1: True |
2 + int(1**2) = 3 |
1932 |
True |
1932 % 10 = 2 |
1932 // 10 = 193 |
2 >= 5: False |
2 % 2 = 0: False |
3 + 2 = 5 |
193 |
True |
193 % 10 = 3 |
193 // 10 = 19 |
3 >= 5: False |
3 % 2 = 1: True |
5 + int(3**2) = 14 |
19 |
True |
19 % 10 = 9 |
19 // 10 = 1 |
9 >= 5: True (continue/skip) |
||
1 |
True |
1 % 10 = 1 |
1 // 10 = 0 |
1 >= 5: False |
1 % 2 = 1: True |
14 + int(1**2) = 15 |
0 |
False |
15 (exit loop) |
Hence, this program prints 15 with a newline character at the end (using the sep parameter in the print() function).