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
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler