Branches and Value Selection
Lesson 10 of 48 in Coddy's Python for C++ Developers course.
Python elif replaces an else if chain. Only the first matching branch runs, so order overlapping conditions by priority. For a value choice, write first if condition else second. C++ puts the condition before ?; Python puts it between the two values. Both evaluate only the chosen result expression. Independent if statements may overwrite a result that an elif chain would leave alone.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
int score = 8;
std::string result = score >= 10 ? "high" : score >= 5 ? "mid" : "low";
std::cout << result << '\n';Python
score = 8
if score >= 10:
result = "high"
elif score >= 5:
result = "mid"
else:
result = "low"
print(result)Porting trap
Do not simulate a conditional with and/or when its true result may be false-valued, such as zero or an empty string.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler