Repeating with for and while
range(5) produces 0, 1, 2, 3 and 4: five numbers, and 5 is not one of them.
Run a three-line loop and watch total grow
Copy this program into IDLE and run it before reading the explanation. Then change the list to your own numbers and run it again.
total = 0
for n in [3, 5, 2]:
total = total + n
print(n, total)
print("done", total)3 3
5 8
2 10
done 10The for line takes the items of the list one at a time. Each time round, the variable n refers to the next item, and the indented lines below run once with that value. One pass through the indented lines is called an iteration. After the last item, Python carries on with the first line that is not indented, so "done" prints once, at the end. A trace table makes the pattern plain.
| Pass | n | total after the pass | Printed |
|---|---|---|---|
| (before) | 0 | ||
| 1 | 3 | 3 | 3 3 |
| 2 | 5 | 8 | 5 8 |
| 3 | 2 | 10 | 2 10 |
| (after) | 10 | done 10 |
The variable total is called an accumulator: it starts at 0 before the loop and collects something on every pass. The line total = total + n is so common that Python has a short form, total += n. Counting works the same way with count += 1.
range() makes the numbers for you
To repeat something a fixed number of times, loop over range(). range(5) gives 0, 1, 2, 3, 4: it starts at 0 and stops before 5, just like a slice. range(1, 6) gives 1 to 5. A third number sets the step, so range(0, 10, 2) gives the even numbers 0 to 8. The multiplication table for 7, which every Korean pupil recites in second grade, is a two-line loop.
for i in range(1, 10):
print(7, "x", i, "=", 7 * i)7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63A for loop can also walk through the characters of a string, which makes counting letters easy.
count = 0
for ch in "banana":
if ch == "a":
count += 1
print(count)3while repeats as long as a condition stays True
A while loop has no list to walk through. It checks a condition, runs the indented lines if it is True, and checks again, over and over. That suits jobs where you do not know the number of passes in advance, such as "keep saving until the total reaches 50,000 won". Something inside the loop must change the condition, or the loop never ends. If that happens, stop the program with Ctrl+C.
saved = 0
weeks = 0
while saved < 50000:
saved += 12000
weeks += 1
print(weeks, saved)5 60000break leaves a loop at once, even in the middle. It is handy when you are searching and can stop as soon as you find what you want. The loop below stops at the first score under 60 and never looks at the 88.
for s in [72, 91, 55, 88]:
if s < 60:
print("first below 60:", s)
break
print("ok", s)ok 72
ok 91
first below 60: 55| for x in ... | Runs the indented lines once for each item |
| range(a, b) | Whole numbers from a up to, not including, b |
| while | Repeats as long as the condition is True |
| accumulator | A variable that collects a total across passes |
| += | total += n is short for total = total + n |
| break | Leaves the loop immediately |
- What does this print?
for i in range(3): print(i)0
1
21
2
30
1
2
33
- What does this print?
total = 0 for n in range(1, 5): total += n print(total) - What does this print?
print(list(range(0, 10, 3))) - What does this print?
total = 0 for n in [1, 2, 3]: total += n print(total)61
3
61
2
30
1
3
- What does this print?
count = 0 for ch in "seoul": if ch in "aeiou": count += 1 print(count) - What does this print?
n = 1 while n < 20: n = n * 2 print(n) - What does this print?
for s in [5, 8, 3, 9]: if s > 6: print(s) break - How many times does this print hi?
for i in range(2, 8): print("hi") - What does this print?
word = "" for ch in "abc": word = ch + word print(word) - Put the lines in order so the program prints the sum of 1 to 100.Output
5050
- "range(1, 10) goes up to 10." It stops before 10, so the last value is 9. For 1 to 10, write range(1, 11).
- "My while loop is fine; it just takes a long time." If nothing inside the loop changes the condition, it never stops. Check that the variable in the condition is updated on every pass, and press Ctrl+C to stop a runaway loop.
- "Putting print inside or outside the loop makes no difference." Indented under the for, it runs on every pass; at the left margin, it runs once after the loop. Decide whether you want every step or only the final answer.
- for x in list: runs the indented lines once per item.
- range(a, b) stops before b; range(n) is 0 to n - 1.
- An accumulator starts before the loop and grows inside it.
- while repeats while a condition is True; something must change it.
- break leaves the loop at once.
Sources for this course (6)
- Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
- Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
- Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
- General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
- Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
- Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)
Checked: 2026-10-19