If Expressions and elif
Lesson 10 of 48 in Coddy's Python for Rust Developers course.
Rust if can produce a value and the branches must have compatible types. Python uses an if statement with elif branches for multiple decisions. Only the first matching branch runs. A compact value selection is written a if condition else b, with the condition in the middle. It evaluates only the selected expression. Python does not statically require both results to have one type, but callers still need to handle whichever object is returned.
Rust excerpt inside main
let score = 8;
let result = if score >= 10 { "high" }
else if score >= 5 { "mid" } else { "low" };
println!("{}", result);Python
score = 8
if score >= 10:
result = "high"
elif score >= 5:
result = "mid"
else:
result = "low"
print(result)Porting trap
Do not replace a conditional expression with condition and a or b when a valid result might be zero or empty text.
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 order total in cents and a membership token, either yes or no. Totals are nonnegative. Shipping is 0 for totals at least 5000, otherwise 200 for members, otherwise 500. Print shipping on line one and free if shipping is zero or paid otherwise on line two. The high-total rule takes priority.
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