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
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler