Menu
CoddyTech

Division and Integer Limits

Lesson 4 of 48 in Coddy's Python for C Developers course.

Since C99, signed integer division truncates toward zero when the result is representable. C therefore gives quotient -2 and remainder -1 for -7 and 3. Python // floors toward negative infinity, giving -3 and 2. Python / produces a float even for integer operands. For nonzero integer b, Python maintains a == (a // b) * b + a % b. Python int grows with the value, subject to memory; C signed integer overflow is undefined behavior, while unsigned arithmetic wraps modulo its type range. Neither language makes floating-point decimal arithmetic exact.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    printf("%d %d\n", -7 / 3, -7 % 3);
    return 0;
}

Python: complete example.py

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

Watch the difference

Do not use int(a / b) to emulate C integer division for huge Python integers: converting through float can lose precision. Convert numeric input explicitly with int; malformed integer text raises ValueError.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Convert two input lines to integers: numerator in [-100,100] and divisor equal to 1, 2, or 4. Output the Python true quotient, then the floor quotient, using default number formatting. These divisors make the quotients exactly representable.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

C signed integer division truncates toward zero; Python floor division rounds down.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler