Bool Conditions and Fallbacks
Lesson 9 of 48 in Coddy's Python for Swift Developers course.
Swift conditions require Bool; a collection must be tested explicitly for emptiness. Python accepts truth tests of many objects: zero, empty built-in collections, empty text, False, and None are false. Python and/or short-circuit and return an operand, whereas Swift logical operators produce Bool. Swift nil-coalescing preserves an optional zero. In Python an explicit None check preserves zero, while a truth-based fallback replaces it.
Swift example
let names: [String] = []
if !names.isEmpty { print("present") }
let limit: Int? = 0
print(limit ?? 10)Python
names = []
if names:
print("present")
limit = 0
print(10 if limit is None else limit)Porting trap
Do not translate Swift nil coalescing mechanically to Python or if false-valued data must be preserved.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerRead a display name and a limit token on two lines. The name may be empty; use Guest only for an empty name. The limit token is missing or an integer from 0 to 20. The scaffold parses it. Use a default limit of 10 only for None, preserving a real zero. Print the selected name and selected integer limit on separate lines.
Print only these lines, ending each with a newline. Keep the supplied input scaffold; it reads the stated values without prompts.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler