Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

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

All lessons in Python for Dart Developers

Practice on your own: Online Python compiler