(Grade IX) Study the Program and answer question
Study the following Python code and
answer the questions below.
a.
num = 5
for x in range(1, 6):
print(num, end="
")
num = num * 10 + 5
i. How many times does the loop execute
in the above program?
The loop executes five times (x = 1, 2,
3, 4, 5).
ii. List all the variables used in the
above program.
The variables used are num and x.
iii. List the operators used in the
above program.
The operators used are =, * and +.
iv. Name the loop used in the above
program.
The loop used in the above program is
the for loop.
b.
n = int(input("Enter a number: "))
s = 0
while n != 0:
r = n % 10
s = s + r
n = n // 10
print("Sum of individual digits is: ", s)
i. Name the loop used in the above
program.
The loop used in the above program is
the while loop.
ii. At what value of n will the loop
terminate?
The loop will terminate when the value
of n is 0.
iii. How many times will the loop
execute if the input number is 5439?
The loop will execute four times if the
input number is 5439 (n = 5439, 543, 54, 5; then n becomes 0). The sum of digits
is 5 + 4 + 3 + 9 = 21.
iv. List all the operators used in the
above program.
The operators used are !=, %, =, + and
//.
c.
n = 10
for i in range(1, n + 1):
if n % i == 0:
print(i)
i. How many times will the loop execute
in the above program?
The loop will execute 10 times (i = 1 to
10).
ii. List the operators used in the above
program.
The operators used are =, +, % and ==.
iii. List all the variables used in the
above program.
The variables used are n and i.
iv. Name the loop used in the above
program.
The loop used is the for loop.
d.
n = 893
s = 0
while n != 0:
r = n % 10
s = s + r
n = n // 10
print("Sum of individual digits is: ", s)
i. Write the function of % in the above
program.
The % (modulus) operator gives the
remainder after dividing by 10. In this program it separates the last digit of
the number (893 % 10 = 3).
ii. Will there be any change if you
replace // with / in the above program?
Yes. "/" gives a decimal
answer (893 / 10 = 89.3) instead of removing the last digit. The number would
never become exactly 0 after three rounds, the remainders would be decimals,
and the sum of digits would be wrong. So // must be used.
iii. Name the loop used in the above
program.
The loop used is the while loop.
iv. How many times will the loop execute
in the above program?
The loop will execute 3 times (one for
each digit of 893).