Menu
CoddyTech

Iteration Without Pointers

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

Python for visits values from an iterable. It has no C-style three-clause header or increment operator. range(start, stop) produces integers up to but excluding stop, so an inclusive ascending interval requires stop + 1. With the default positive step, a larger start produces no values. range(5, 0, -2) supplies 5, 3, 1 without building a list first. Iterating a list gives elements rather than indexes unless you ask for indexes.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    for (int i = 2; i < 5; ++i) printf("%d\n", i);
    return 0;
}

Python: complete example.py

for i in range(2, 5):
    print(i)

Watch the difference

Rebinding the Python loop variable does not replace a list element. In C, writing through a pointer can change array storage; in Python use indexed assignment or mutate the referenced element deliberately.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Read start and stop integers, both in [-100,100]. Output the sum over the inclusive ascending interval, or zero if start exceeds stop.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

A C loop with i <= stop corresponds to range(start, stop + 1); range excludes its stop.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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 C Developers

Practice on your own: Online Python compiler