From end to Indentation
Lesson 5 of 48 in Coddy's Python for Ruby Developers course.
A Ruby if suite ends with end; indentation is for the reader. Python ends the suite by dedenting. A colon introduces the suite and four spaces per level are the usual style. Neither a Ruby if nor a Python if creates a separate local-variable scope. There is a subtle initialization difference: Ruby recognizes an assignment in a skipped branch as introducing a local and reads it as nil. Python does not bind a value until the assignment executes. At module scope, reading such an absent Python name raises NameError; inside a function it can raise UnboundLocalError.
Ruby
if false
stock = 7
end
p stockPython
if False:
stock = 7
try:
print(stock)
except NameError:
print('unbound')Porting trap
Initialize a fallback before a conditional when later code needs the name. Do not rely on Ruby's skipped-assignment nil behavior.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler