AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumpythonoperators

~75s

Three divisions in Python

What does this Python program print?

print(7 // 2, 7 / 2, -7 // 2)
Show the answer and the worked solution

Correct answer: B.

3 3.5 -4

Worked solution

  1. 7 // 2 is floor division and gives the integer 3.
  2. 7 / 2 is true division and always gives a float, here 3.5.
  3. -7 // 2 floors -3.5 downwards to -4, so the line prints 3 3.5 -4.

Answer: 3 3.5 -4.

The idea

Python 3 separates true division from floor division, and floor division rounds towards minus infinity. That last rule is what makes the negative case differ from C, where the same expression gives -3.

Shortcut. / always returns a float (3.5) and // floors towards minus infinity, so −3.5 becomes −4, not −3.

Common trap. "3 3.5 -3" truncates −3.5 towards zero as C does; Python's // rounds down, to −4.

Three divisions in Python — Aptitude Question

Three divisions in Python: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

print(7 // 2, 7 / 2, -7 // 2)

Options

  1. 3 3.5 -3
  2. 3 3.5 -4
  3. 3 3 -4
  4. 3.5 3.5 -3.5
Show the answer and the worked solution

Correct answer: B. 3 3.5 -4

Worked solution

  1. 7 // 2 is floor division and gives the integer 3.
  2. 7 / 2 is true division and always gives a float, here 3.5.
  3. -7 // 2 floors -3.5 downwards to -4, so the line prints 3 3.5 -4.

Answer: 3 3.5 -4.

The idea

Python 3 separates true division from floor division, and floor division rounds towards minus infinity. That last rule is what makes the negative case differ from C, where the same expression gives -3.

Shortcut. / always returns a float (3.5) and // floors towards minus infinity, so −3.5 becomes −4, not −3.

Common trap. "3 3.5 -3" truncates −3.5 towards zero as C does; Python's // rounds down, to −4.

All Programming Fundamentals questions · placement mock tests