What will be the value of x after the following code is executed:

x = 10

y = 5

x += y * 2

x -= y // 2

x *= y % 2

print(x)

Options:

a. 18

b. 10

c. 20

d. 30

Answer:

Answer by student

a. 18

Detailed answer by teachoo

-lock-

Let’s go through each of the options and see why they are correct or incorrect.

  • Option a. 18: This is the correct answer. We will explain how to get this value in the next steps.
  • Option b. 10: This is incorrect . This would be the value of x if we only executed the first line of code, x = 10, and ignored the rest.
  • Option c. 20: This is incorrect . This would be the value of x if we only executed the first two lines of code, x = 10 and y = 5, and then added x and y, which is not what the code does.
  • Option d. 30: This is incorrect . This would be the value of x if we only executed the first three lines of code, x = 10, y = 5 and x += y * 2, and then added x and y, which is also not what the code does.

Now, let’s see how to get the correct answer by following the code step by step.

  • The first line of code assigns the value 10 to x:

 x = 10

  • The second line of code assigns the value 5 to y: 

y = 5

  • The third line of code uses the augmented assignment operator +=, which adds the right operand to the left operand and assigns the result to the left operand. In this case, it adds y * 2, which is 5 * 2 or 10 , to x and assigns the result to x. 

So, x becomes 20: x += y * 2

  • The fourth line of code uses the augmented assignment operator -=, which subtracts the right operand from the left operand and assigns the result to the left operand. In this case, it subtracts y // 2, which is 5 // 2 or 2 , from x and assigns the result to x.

 So, x becomes 18 : x -= y // 2

  • The fifth line of code uses the augmented assignment operator *=, which multiplies the right operand with the left operand and assigns the result to the left operand. In this case, it multiplies x with y % 2, which is 5 % 2 or 1 , and assigns the result to x. 

So, x becomes 18 : x *= y % 2

  • The sixth line of code prints the value of x, which is 18: print(x)

So, the final value of x is 18 , which matches option a. 18.

So, the correct answer is option a. 18

-endlock-

Remove Ads
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.