Truth Tests and Fallbacks
Lesson 9 of 48 in Coddy's Python for Rust Developers course.
Rust conditions require bool; a collection must be tested with operations such as is_empty. Python directly tests empty lists, strings, zero, and None as false. Python and and or short-circuit and return an operand, not necessarily a boolean. Rust && and || require booleans and yield a boolean. If zero is valid data, use an explicit absence check rather than a truth-based fallback. An Option can distinguish Some(0) from None in Rust.
Rust excerpt inside main
let names: Vec<String> = Vec::new();
if !names.is_empty() { println!("present"); }
let limit = Some(0);
println!("{}", limit.unwrap_or(10));Python
names = []
if names:
print("present")
limit = 0
print(10 if limit is None else limit)Porting trap
Python limit or 10 replaces a legitimate zero. The expression 10 if limit is None else limit preserves it.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler