Menu
CoddyTech

Foreach and range

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

PHP foreach can bind an element by reference with &. Python for loops bind a local name to each element; rebinding that name does not replace a list slot. Mutating a mutable element is different from rebinding the loop name. Python range(start, stop) excludes stop, unlike PHP range with its inclusive endpoint. A Python range is an iterable sequence rather than a newly allocated list of every integer.

PHP 8.3

<?php
$values = [2, 4];
foreach ($values as &$value) { $value += 1; }
unset($value);
echo implode(' ', $values), "\n";

Python

values = [2, 4]
for value in values:
    value += 1
print(*values)

Porting trap

A PHP foreach reference can remain attached to the final element after the loop, which is why PHP code often calls unset($value). Python has no corresponding foreach-by-reference syntax. Use indexed assignment or a new comprehension to replace integer elements.

Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.

challenge icon

Challenge

Beginner

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

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

All lessons in Python for PHP Developers

Practice on your own: Online Python compiler