Suites Instead of Braces
Lesson 5 of 48 in Coddy's Python for C Developers course.
C braces group statements into a block. Python uses a colon and indentation to form a suite, and dedenting ends it. Use four spaces consistently. Moving the final print into the indented suite makes it conditional. Parentheses around a simple Python condition are optional, and statement-ending semicolons are unnecessary. Unlike a C compound block, a Python if suite does not establish a separate local variable scope. A name assigned in a branch exists afterwards only if that assignment actually ran.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
int stock = 7;
if (stock > 5) { puts("bulk"); }
puts("done");
return 0;
}Python: complete example.py
stock = 7
if stock > 5:
print("bulk")
print("done")Watch the difference
Do not carry C braces into a Python if. Curly braces construct dictionaries or sets in expressions. A missing assignment on one branch is not fixed by indentation alone.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerA nonnegative stock count is supplied. Output audit; when stock exceeds 5, also output bulk and the count on two lines; finally always output done. Repair the starter's block layout and complete its prints.
Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.
Python indentation takes over the grouping role of C braces.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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 C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler