Option and None
Lesson 7 of 48 in Coddy's Python for Rust Developers course.
Rust expresses optional data with Option<T> and normally handles its variants by matching or combinators. Python commonly uses a value or the singleton None. There is no wrapper to unwrap before using a nonmissing value, and no compiler forces you to handle absence. Use is None to detect missing data. Python booleans are spelled True and False. A count of zero is valid data even though it is false in a Python condition.
Rust excerpt inside main
let seats: Option<i32> = None;
println!("{}", seats.is_none());
println!("{}", false);Python
seats = None
print(seats is None)
available = False
print(available)Porting trap
An empty container, zero, and None all test false in Python. An absence check should not accidentally reject valid empty or zero values.
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 an integer seat count from 0 to 20. Print whether any seats remain, using Python's boolean spelling. On the next line print the count if it is positive, or None if it is zero. Initialize the reported value to None and replace it when seats remain.
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