Menu
CoddyTech

Integers and Floor Division

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

Rust integer widths are fixed. Python int grows with the magnitude, subject to memory, so arithmetic does not wrap at a machine-word boundary. Rust integer / truncates toward zero. Python // floors toward negative infinity and % has the divisor's sign for nonzero remainders. Thus the negative examples differ while each quotient and remainder reconstructs the dividend. Python / produces a float even for integer operands; int(text) parses integer text and raises ValueError on invalid input.

Rust excerpt inside main

println!("{}", -7 / 3);
println!("{}", -7 % 3);

Python

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

Porting trap

Rust div_euclid agrees with Python floor division for positive divisors but not for every negative divisor. Choose the rounding rule explicitly when porting.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

Read an integer numerator and a positive integer divisor on separate lines. Convert both input strings to integers. Print true division on line one and floor division on line two. Numerators are between -100 and 100; divisors are 1, 2, or 4, so the quotients have exact binary representations. Use Python's default printed number format.

Print only the requested output, with a newline after each line. The supplied input lines read the test data; keep them and add your work below.

Your code goes in main.py. The locked driver.py starts your program 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 Rust Developers

Practice on your own: Online Python compiler