Conditional Value Selection
Lesson 10 of 48 in Coddy's Python for C Developers course.
Python if/elif/else expresses the same first-match priority as a C if/else-if chain. Test higher-priority cases first. Two independent if statements can both run, so the later one may overwrite a result. For a short value choice, Python writes first if condition else second instead of the C condition ? first : second form. Only the selected result expression is evaluated. Keep else at the indentation level of its matching if.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
int score = 8;
const char *label = score >= 10 ? "high" : score >= 5 ? "mid" : "low";
puts(label);
return 0;
}Python: complete example.py
score = 8
if score >= 10:
label = "high"
elif score >= 5:
label = "mid"
else:
label = "low"
print(label)Watch the difference
Do not emulate a conditional with and/or when the first result can be zero or empty. Those values would trigger the fallback even when the condition is true.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerRead a nonnegative total in cents and a membership token yes or no. Shipping costs 0 for totals at least 5000; otherwise it costs 200 for a member and 500 for a nonmember. Output the shipping number and then free for zero or paid otherwise.
Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.
Keep the priority of the C if/else-if chain when writing Python if/elif.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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 Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler