Repeat work with loops
Use for and while loops to process repeated steps.
- Loop over a range and accumulate a result.
A for loop visits each item in an iterable. range(stop) produces numbers from zero up to, but not including, stop. A while loop repeats while its condition remains true.
for number in range(1, 4):
print(number)1 2 3
Loops prevent repeated copy-and-paste code. Indentation defines the loop body. Make sure a while loop changes something that can eventually make its condition false.
Key takeaways
Loop over a range and accumulate a result.
Read the output to check what your program did.
Keep indentation consistent in Python blocks.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Python
Write Python in the editor and run it against sample inputs. Python runs locally in your browser using a WebAssembly runtime.
Add the numbers
Read a non-negative integer n and print the sum of all integers from 1 through n (print 0 when n is 0).
- Sum through 5
- Zero
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…