Ranges and Loop Bindings
Lesson 17 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin's 2..5 range includes five; Python range(2, 5) excludes five. Kotlin until also excludes its upper bound. Both basic for forms visit iterable values rather than expose writable list slots. Python loop names can be rebound, but rebinding an integer loop name does not replace the stored list element. Mutating a referenced mutable element is a separate operation.
Kotlin
fun main() {
println((2..5).joinToString(" "))
}Python
values = [2, 4]
for value in values:
value += 1
print(*values)Porting trap
Check range endpoints when porting loops. Empty Python ranges naturally produce no values when start is at or beyond stop for a positive step.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler