Python Lab

Stage 1 · 30 min · Free

for and while loops

Repeat work with for and range(), while, running totals, break and continue.

Objectives

Why learn this

Computers are best at doing things over and over without getting tired. Printing 100 lines, adding up 1000 numbers, going through a list of learners: all of them need loops.

Concept

for i in range(n): repeats n times with i = 0, 1, ..., n-1. range(a, b) goes from a to b-1. range(a, b, step) jumps by step.

while condition: repeats as long as the condition is true. Something inside must eventually make the condition false, or it loops forever (the grader stops it after a few seconds).

Running-total pattern: set total = 0 before the loop, and each time round do total = total + value.

break leaves the loop immediately; continue skips the rest of the current iteration.

Syntax

for i in range(1, 6):
    print(i)

while n > 0:
    n = n - 1

Example

n = int(input())
tong = 0
for i in range(1, n + 1):
    tong = tong + i
print("Tổng 1 đến", n, "là", tong)

Input:

5

Output:

Tổng 1 đến 5 là 15

Line-by-line explanation

  1. Line 1: n = 5.
  2. Line 2: tong starts at 0.
  3. Line 3: i goes 1, 2, 3, 4, 5 (range stops before n + 1 = 6).
  4. Line 4: each time, i is added to tong: 1, 3, 6, 10, 15.
  5. Line 5: printed only after the loop (this line is NOT indented).

Common mistakes

for i in range(1, 5):  # muốn 1..5

range stops before the last number, so you only get 1..4.

range(1, 6) hoặc range(1, n + 1)
while i < 5:
    print(i)

i is never increased, so it loops forever.

Thêm i = i + 1 trong vòng lặp.
for i in range(5):
    tong = 0
    tong = tong + i

Setting tong = 0 inside the loop resets the total every time.

Đặt tong = 0 trước vòng for.

Summary

2 practice tasks and 3 quiz questions

Write code right in the browser; the grader runs real Python and points to the exact line that's wrong.

Practice for free