GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Result of integer division may be truncated — CodeQL query help documentation

Result of integer division may be truncated¶

ID: py/truncated-division
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - maintainability
   - correctness
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

In Python 2, the result of dividing two integers is silently truncated into an integer. This may lead to unexpected behavior.

Recommendation¶

If the division should never be truncated, add from __future__ import division to the beginning of the file. If the division should always be truncated, replace the division operator / with the truncated division operator //.

Example¶

The first example shows a function for calculating the average of a sequence of numbers. When the function runs under Python 2, and the sequence contains only integers, an incorrect result may be returned because the result is truncated. The second example corrects this error by following the recommendation listed above.

# Incorrect:

def average(l):
    return sum(l) / len(l)

print average([1.0, 2.0])  # Prints "1.5".
print average([1, 2])      # Prints "1", which is incorrect.
# Correct:
from __future__ import division

def average(l):
    return sum(l) / len(l)

print average([1.0, 2.0])  # Prints "1.5".
print average([1, 2])      # Prints "1.5".

References¶

  • Python Language Reference: Binary arithmetic operations.

  • PEP 238: Changing the Division Operator.

  • PEP 236: Back to the future.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.