Conditions and Null Defaults
Lesson 9 of 48 in Coddy's Python for Dart Developers course.
Dart conditions require bool; integers, strings, and collections cannot be used as implicit truth values. Python truth-tests these objects: zero and empty containers are false-valued. Dart logical operators take boolean operands and return booleans. Python and/or return selected operands and can therefore implement a truth-based fallback. Dart null-coalescing supplies a fallback only for null; Python or also replaces zero and empty values. Use a conditional expression with is None when translating a null-only default. Both languages short-circuit, but they differ in which inputs are accepted and how the selected result is determined.
Dart
void main() {
int? limit = 0;
print(limit ?? 10);
limit = null;
print(limit ?? 10);
}Python
print(0 or 10)
print('' or 'empty')Porting trap
Dart null-coalescing and Python or are not interchangeable. A legitimate zero is preserved by the former and replaced by the latter.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler