Menu
CoddyTech

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 stock

Python

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

Practice on your own: Online Python compiler