Menu
CoddyTech

From foreach to for

Lesson 17 of 48 in Coddy's Python for C# Developers course.

Translate loop bounds into Python iteration without off-by-one errors.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

int total = 0;
for (int i = 2; i < 5; i++) total += i;
Console.WriteLine(total);

Python

total = 0
for value in range(2, 5):
    total += value
print(total)

What changes

Python for takes successive values from an iterable, much like C# foreach. range(start, stop) excludes stop. Use stop + 1 for an inclusive upper integer bound. range itself is not a prebuilt list. A positive-step range with start greater than stop has no elements, so an accumulator initialized to zero remains zero.

Transfer mistake

Python has no i++ increment syntax. Also, the loop target remains bound after a nonempty loop in the surrounding scope; do not assume C# for-local scope.

Your task

Read start and stop integers, each in [-100, 100]. Sum every integer from start to stop inclusive. If start exceeds stop, the sum is 0. Output the integer total on one line. Translate the boundary deliberately rather than copying a C# loop condition mechanically.

challenge icon

Challenge

Beginner

Read start and stop integers, each in [-100, 100]. Sum every integer from start to stop inclusive. If start exceeds stop, the sum is 0. Output the integer total on one line. Translate the boundary deliberately rather than copying a C# loop condition mechanically.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C# Developers

Practice on your own: Online Python compiler