elsif and Conditional Values
Lesson 10 of 48 in Coddy's Python for Ruby Developers course.
Python uses elif where Ruby uses elsif. An ordered branch chain runs only its first matching branch, so put more specific cases before overlapping general cases. Ruby can assign the value of an entire if expression. Python if statements do not produce a value; either assign within each branch or use yes_value if condition else no_value. That expression places the condition between the alternatives, unlike Ruby's condition ? yes_value : no_value. Only the selected result is evaluated. Avoid substituting a logical-operator chain for conditional selection when the chosen result can be false-valued.
Ruby
ready = true
puts(ready && 0 || 5)Python
ready = True
print(ready and 0 or 5)
print(0 if ready else 5)Porting trap
Ruby ready && 0 || 5 preserves zero, but the same idea with Python and and or does not. Use the conditional expression for value selection.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler