Branches and Ternaries
Lesson 10 of 48 in Coddy's Python for Swift Developers course.
Python elif replaces Swift else if, with a colon before each suite. Only the first matching branch runs. The Python conditional expression is a if condition else b, with the condition between the results, unlike Swift condition ? a : b. It evaluates only the chosen result. Use it when selecting a value, and a statement chain when each branch performs several operations. Python does not require branch results to share one static type.
Swift example
let score = 8
let result = score >= 10 ? "high" : score >= 5 ? "mid" : "low"
print(result)Python
score = 8
if score >= 10:
result = "high"
elif score >= 5:
result = "mid"
else:
result = "low"
print(result)Porting trap
A truth-based and/or expression is not a safe ternary replacement when the true result might be zero.
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 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