Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

Python will not floor-divide text by a whole number

Your error

TypeError: unsupported operand type(s) for //: 'str' and 'int'2 more lines it can show

Fix it fast

Most common cause, 1 of 3

The number was typed in through input()

Convert the text once, right where you read it. int() accepts surrounding spaces and a newline, and raises ValueError for text that is not a whole number, so catch that and ask again.

Fix
while True:
    try:
        minutes = int(input("Minutes: "))
        break
    except ValueError:
        print("Please type a whole number.")
hours, rest = minutes // 60, minutes % 60
print(hours, rest)
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

TypeError: unsupported operand type(s) for //: 'str' and 'int' means the value on the left of // is text that only looks like a number. input(), sys.argv, os.environ and csv.reader all return strings, and Python does not convert them for you. Wrap the value in int() or float() before the arithmetic, for example int(input()) // 2. Applies to Python 3.15.

  • Applies to Python 3.15.2
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Print the type and the exact value of both operands on the line before the failing one. The source of the str value (keyboard, command line, environment, file) tells you which cause applies.

Run this first
print(type(minutes), repr(minutes), type(60), repr(60))

Then find the line you see in this list and open its fix:

  1. 1The number was typed in through input()repr() shows quotes around the value, for example '125', and the value comes from input()
  2. 2The number arrives from the command line or an environment variableThe value comes from sys.argv[...] or os.environ[...] / os.getenv(...)
  3. 3The numbers are read from a CSV fileThe value is a field of a row from csv.reader or csv.DictReader

What does the error look like?

  • TypeError: unsupported operand type(s) for //: 'str' and 'int'
  • TypeError: unsupported operand type(s) for /: 'str' and 'int'
  • TypeError: unsupported operand type(s) for -: 'str' and 'int'

Cause 1 of 3

The number was typed in through input()

You seerepr() shows quotes around the value, for example '125', and the value comes from input()

Check

This TypeError appears when a value read with input() meets // and an int. The Python docs say input() reads a line, converts it to a string with the trailing newline stripped, and returns that string. '125' // 60 is therefore text divided by a number, which Python refuses.

Check
minutes = input("Minutes: ")
print(type(minutes))   # <class 'str'>

Fix

Convert the text once, right where you read it. int() accepts surrounding spaces and a newline, and raises ValueError for text that is not a whole number, so catch that and ask again.

Fix
while True:
    try:
        minutes = int(input("Minutes: "))
        break
    except ValueError:
        print("Please type a whole number.")
hours, rest = minutes // 60, minutes % 60
print(hours, rest)

Verify

Typing 125 prints 2 5 instead of a traceback.

Verify
echo 125 | python3 timer.py

Confirmed by docs.python.org

Did this fix it?

Cause 2 of 3

The number arrives from the command line or an environment variable

You seeThe value comes from sys.argv[...] or os.environ[...] / os.getenv(...)

Check

sys.argv is the list of command-line arguments as strings, and os.environ maps names to string values. A script run as python3 split.py 10, or with WORKERS=4 in its environment, receives '10' and '4', never the numbers 10 and 4.

Check
python3 -c "import sys, os; print(repr(sys.argv[1:]), repr(os.environ.get('WORKERS')))" 10

Fix

Turn the text into a number as soon as it is read. For options, let argparse do it with type=int; it reports a clean error when the text is not a number.

Fix
import argparse, os

parser = argparse.ArgumentParser()
parser.add_argument("total", type=int)
args = parser.parse_args()

workers = int(os.environ.get("WORKERS", "4"))
print(args.total // workers)

Verify

python3 split.py 10 prints 2 with the default of 4 workers, and python3 split.py ten exits with an argparse usage error instead of a TypeError.

Verify
python3 split.py 10

Confirmed by docs.python.org

Did this fix it?

Cause 3 of 3

The numbers are read from a CSV file

You seeThe value is a field of a row from csv.reader or csv.DictReader

Check

Python's csv module returns every row as a list of strings and performs no type conversion of its own. The only exception is the QUOTE_NONNUMERIC option, which turns unquoted fields into floats. A column of quantities is still text when you divide it.

Check
import csv
with open("stock.csv", newline="") as f:
    row = next(csv.reader(f))
    print([type(v).__name__ for v in row])

Fix

Convert the fields you calculate with, by column. Use float() for decimals. If every unquoted field in the file is numeric, quoting=csv.QUOTE_NONNUMERIC converts them all to floats in one step.

Fix
import csv
with open("stock.csv", newline="") as f:
    for name, qty, per_box in csv.reader(f):
        boxes = int(qty) // int(per_box)
        print(name, boxes)

Verify

The loop prints a whole number of boxes for every row, and a bad cell raises ValueError naming that text.

Verify
python3 boxes.py

Confirmed by docs.python.org

Did this fix it?

How do I stop it coming back?

  • Convert outside data to numbers at the boundary (the line that reads input, argv, env or a file), never deep inside the calculation.
  • Keep a small test that feeds the parsing code sample text such as '125' and ' 7\n' and asserts that an int comes back.
  • Use argparse type=int for command-line numbers instead of reading sys.argv by hand.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.