ifelse and Scalar Selection
Lesson 10 of 48 in Coddy's Python for R Developers course.
R if can return a branch value, and ifelse performs vectorized selection over a test vector. Python's ordinary if is a statement; its conditional expression selects one value using the form yes if condition else no. It is scalar control flow, not a vectorized replacement for R ifelse. Python elif builds a branch chain where only the first matching branch runs. Nested conditions need deliberate priority when ranges overlap. In R, ifelse can evaluate each value expression when any element needs it; Python's conditional expression evaluates only the selected expression. Use a comprehension for per-element scalar decisions.
R
ready <- TRUE
cat(if (ready) 0 else 5, "\n", sep="")
cat(ifelse(c(TRUE, FALSE), 0, 5), "\n")Python
ready = True
print(ready and 0 or 5)
print(0 if ready else 5)Porting trap
Do not use a chain of and/or as a conditional expression when the selected result may be zero or empty.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler