Menu
CoddyTech

Braces Become Suites

Lesson 5 of 48 in Coddy's Python for R Developers course.

R groups statements with braces; Python uses a colon and indentation. Dedenting ends a Python suite, so whitespace can change behavior rather than only presentation. Neither an R if block nor a Python if block introduces a new function scope. A name assigned only in a branch that never runs is not safe to read afterward. R searches enclosing environments for unresolved names; Python also has scope lookup, but assignment inside a function normally makes a name local for that entire function. That can produce UnboundLocalError if it is read before assignment. Initialize needed defaults before a conditional.

R

if (FALSE) {
  stock <- 7
}
cat(exists("stock", inherits=FALSE), "\n", sep="")

Python

if False:
    stock = 7
try:
    print(stock)
except NameError:
    print('unbound')

Porting trap

A visual indentation change without moving R braces may be cosmetic; the corresponding Python change can move a statement into or out of a branch.

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 R Developers

Practice on your own: Online Python compiler