Indentation and Scope
Lesson 5 of 48 in Coddy's Python for Rust Developers course.
Python starts a suite with a colon and groups its statements by indentation. Dedenting ends the suite. Use four spaces consistently. Unlike Rust braces, Python if and for suites do not create a new local scope. A name assigned inside them belongs to the surrounding function or module. A skipped assignment does not create a usable value, so a name assigned only in one branch may still be unbound afterward. Python functions, unlike these suites, do introduce local scope.
Rust excerpt inside main
let stock = 7;
if stock > 5 {
println!("bulk");
}
println!("done");Python
stock = 7
if stock > 5:
print("bulk")
print("done")Porting trap
A Rust block can yield a tail expression. A Python suite does not implicitly return its final expression; functions need return when a result is wanted.
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 a nonnegative integer stock level. Print audit first. If stock is greater than 5, print bulk and then the stock number. Always print done last. Repair the block layout and add the missing output; no other lines should appear.
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