Informatics Practices

Find the output of the following code:

p = 21 // 5
q = p % 4
r = p * q
p+= p + q - r
r*= p - q + r
q+= p + q
print(p, q, r)

Python Funda

1 Like

Answer

8 8 0

Working

p = 21 // 5

The floor division // operator divides and returns the integer quotient of the division.

  • ( 21 // 5 = 4 )
  • Thus, ( p = 4 )
q = p % 4

Here, the modulo % operator calculates the remainder of the division.

  • ( p \% 4 = 4 \% 4 = 0 )
  • Thus, ( q = 0 )
r = p * q

Now it performs a multiplication.

  • p x q = 4 x 0 = 0
  • Thus, r = 0
p += p + q - r

The += operator adds the value on the right to the variable and assigns it to the variable again.

  • Initially, ( p = 4 )
  • Calculation inside the parentheses: ( p + q - r = 4 + 0 - 0 = 4 )
  • p += 4 means p = p + 4
  • So, p = 4 + 4 = 8
r *= p - q + r

The *= operator multiplies the variable by the value on the right and assigns it to the variable again.

  • Initially, ( r = 0 )
  • Calculation inside the parentheses: ( p - q + r = 8 - 0 + 0 = 8 )
  • r *= 8 means r = r x 8
  • So, r = 0 x 8 = 0
q += p + q

The += operator adds the value on the right to the variable and assigns it to the variable again.

  • Initially, q = 0
  • Calculation inside the parentheses: p + q = 8 + 0 = 8
  • q += 8 means q = q + 8
  • So, q = 0 + 8 = 8
print(p, q, r)

The variables now have these final values:

  • p = 8
  • q = 8
  • r = 0

Hence, the output of the program is:

8 8 0

Answered By

1 Like


Related Questions