What will be the output of the following code:
a = 20
b = 10
if a % b == 0:
a = a // b
b = a * b
else:
a = a * b
b = a // b
print(a, b)
A) 2 20
B) 20 2
C) 200 10
D) 10 200
Answer:
Answer by student
A) 2 20
Detailed answer by teachoo
-lock-
Let’s go through each of the options and see why they are correct or incorrect.
- Option A) 2 20
This is the correct option. To understand why, let’s trace the execution of the code.
The code starts with assigning the values 20 and 10 to the variables a and b respectively.
Then, it checks the condition a % b == 0 , which means if a is divisible by b. In this case, 20 is divisible by 10, so the condition is true.
Therefore, the code executes the statements inside the if block , which are:
a = a // b : This assigns the value of a divided by b using integer division to a. Integer division means that the result is rounded down to the nearest integer. So, a // b is equal to 20 // 10, which is 2. Hence, a becomes 2.
b = a * b : This assigns the value of a multiplied by b to b. So, a * b is equal to 2 * 10, which is 20. Hence, b becomes 20.
Finally, the code prints the values of a and b, which are 2 and 20 respectively. So, the output is 2 20.
- Option B) 20 2
This is incorrect . This would be the output if the condition was false and the code executed the else block instead of the if block.
- Option C) 200 10
This is incorrect . This would be the output if the code executed both the if and else blocks, which is not possible.
- Option D) 10 200
This is incorrect . This would be the output if the code swapped the values of a and b before executing the if block.
So, the correct answer is A) 2 20.
-endlock-