each and Python for
Lesson 17 of 48 in Coddy's Python for Ruby Developers course.
Ruby commonly iterates with each and a block; Python uses a for statement over an iterable. Python has no block parameter bars. The loop target receives each element, not its index. Rebinding a target containing an integer does not replace the element in either example. Use a transformation or indexed assignment to change stored numbers. Python range(start, stop) excludes stop, like a Ruby range with three dots. A Ruby two-dot range includes its endpoint. Python loop targets remain in the surrounding scope after a nonempty loop; a Ruby each block's parameter is local to that block.
Ruby
values = [2, 4]
values.each { |value| value += 1 }
p values
p (0..2).to_aPython
values = [2, 4]
for value in values:
value += 1
print(values)
print(list(range(0, 2)))Porting trap
Translate a Ruby inclusive range deliberately: use stop plus one in Python when the endpoint should be included. An empty range has no iterations.
Challenge
BeginnerRead two integer lines, start then stop, each between -100 and 100. Print the sum of all integers from start through stop, inclusive. If start > stop, print 0. Print one integer and a newline. Keep the supplied input scaffold.
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