Braces and Block Scope
Lesson 5 of 48 in Coddy's Python for Dart Developers course.
Dart uses braces for statement blocks and gives local declarations block scope. Python uses indentation after a colon, and if or for suites do not introduce a separate local scope. A variable assigned inside an executed Python if remains available in the surrounding scope. A skipped assignment does not bind a value, so later access can fail. Dart static analysis checks many uninitialized or out-of-scope reads before execution; Python discovers these when the affected path runs. Use consistent spaces and initialize fallbacks before conditional assignments when later statements need them.
Dart
void main() {
var stock = 1;
if (true) {
final stock = 7;
print(stock);
}
print(stock);
}Python
if False:
stock = 7
try:
print(stock)
except NameError:
print('unbound')Porting trap
Removing braces is not enough to port a block. Reconsider both indentation and the lifetime of names introduced inside it.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler