Files, Sorting & Records — The 100-Student Problem

This whole lesson is one problem. Every new thing you learn here shows up because the problem refuses to be solved without it. Cả bài học này chỉ có một bài toán. Mỗi thứ mới bạn học đều xuất hiện vì bài toán không thể giải nếu thiếu nó.

🛠️ Section 0 — Set Up Your Computer

Do this once. Follow the numbered steps in order. Làm một lần. Làm theo các bước đánh số, đúng thứ tự.

0.1 — Install Git Bash

Git Bash is the window where you type commands. Git Bash là cửa sổ để gõ lệnh.

  1. Go to git-scm.com/install/windows and click "Click here to download". Vào git-scm.com/install/windows, bấm "Click here to download".
    The Git download page with Click here to download circled in red
    Click the link in the red box. / Bấm liên kết trong khung đỏ.
  2. Open File Explorer → Downloads → double-click the file. Mở File Explorer → Downloads → bấm đúp vào tệp.
  3. If Windows asks "Do you want to allow this app to make changes?", click Yes. Nếu Windows hỏi, bấm Yes.
  4. Click Next on every screen, then Install, then Finish. Bấm Next ở mọi màn hình, rồi Install, rồi Finish.
  5. To open Git Bash: Start → type Git Bash → click it. Để mở Git Bash: Start → gõ Git Bash → bấm vào.
    An empty Git Bash window waiting for a command
    Git Bash. The $ means it is waiting for you to type. / Dấu $ nghĩa là nó đang chờ bạn gõ. (Image: gitforwindows.org)

0.2 — Install Python

  1. Go to python.org/downloads/windows. Vào python.org/downloads/windows.
  2. Find the first Python 3.14 and click "Windows installer (64-bit)" — not "Python install manager". Tìm Python 3.14 đầu tiên, bấm "Windows installer (64-bit)" — không phải "Python install manager".
    The Python download page with Windows installer (64-bit) circled in red
    Click the link in the red box. / Bấm liên kết trong khung đỏ.
  3. Open File Explorer → Downloads → double-click the file. Mở File Explorer → Downloads → bấm đúp vào tệp.
  4. If Windows asks "Do you want to allow this app to make changes?", click Yes. Nếu Windows hỏi, bấm Yes.
  5. Tick "Add python.exe to PATH" at the bottom. Do not skip this. Tích ô "Add python.exe to PATH" ở dưới cùng. Không được bỏ qua.
    The Python installer with the Add to PATH checkbox circled in red
    Tick the box in the red frame. Your version number will be newer. / Tích ô trong khung đỏ. Số phiên bản của bạn sẽ mới hơn. (Image: docs.python.org)
  6. Click Install Now, then Close. Bấm Install Now, rồi Close.

0.3 — Install VS Code

VS Code is where you write your code. VS Code là nơi bạn viết code.

  1. Go to code.visualstudio.com/download and click the Windows button. Vào code.visualstudio.com/download, bấm nút Windows.
    The VS Code download page with the Windows button circled in red
    Click the button in the red box. / Bấm nút trong khung đỏ.
  2. Open File Explorer → Downloads → double-click the file. Mở File Explorer → Downloads → bấm đúp vào tệp.
  3. Click "I accept the agreement", then Next. Bấm "I accept the agreement", rồi Next.
  4. On "Select Additional Tasks", tick both "Add 'Open with Code'" boxes. Ở màn hình "Select Additional Tasks", tích cả hai ô "Add 'Open with Code'".
    The VS Code installer with the two Open with Code boxes circled in red
    Tick both boxes in the red frame — they start empty. / Tích cả hai ô trong khung đỏ — lúc đầu còn trống. (Image: MIT RACECAR course, MIT License)
  5. Click Next, Install, Finish. Bấm Next, Install, Finish.

0.4 — Make a folder and open it in VS Code

  1. Open File Explorer → This PC → double-click the (D:) disk. (No (D:) disk? Tell your teacher.) Mở File Explorer → This PC → bấm đúp vào ổ (D:). (Không có ổ D:? Báo giáo viên.)
  2. Right-click an empty space → New → Folder. Name it with your name — no spaces, no accents. Example: nguyenvanan. Bấm chuột phải vào chỗ trống → New → Folder. Đặt tên bằng tên của bạn — không dấu cách, không dấu tiếng Việt. Ví dụ: nguyenvanan.
  3. Right-click your folder → Open with Code. (No option? Click "Show more options" first.) Bấm chuột phải vào thư mục của bạn → Open with Code. (Không thấy? Bấm "Show more options" trước.)
  4. VS Code asks if you trust the folder. Click "Yes, I trust the authors". VS Code hỏi bạn có tin thư mục không. Bấm "Yes, I trust the authors".
    The VS Code question Do you trust the authors of the files in this folder
    Click the blue button. / Bấm nút màu xanh. (Image: VS Code documentation)
  5. In the left panel of VS Code, right-click an empty space → New Folder.... Type helloworld and press Enter. All your files for this lesson go in this folder. Ở khung bên trái VS Code, bấm chuột phải vào chỗ trống → New Folder... Gõ helloworld rồi nhấn Enter. Mọi tệp của bài này đều để trong thư mục này.

0.5 — Create your first file

  1. In the left panel of VS Code, click the helloworld folder. Ở khung bên trái VS Code, bấm vào thư mục helloworld.
  2. Click the New File button (a page with +). Bấm nút New File (tờ giấy có dấu +).
    The VS Code Explorer with the New File button highlighted
    The New File button, in the green box. Yours shows your name on top. / Nút New File, trong khung xanh lá. Của bạn ghi tên bạn ở trên cùng. (Image: VS Code documentation)
  3. Type hello.py and press Enter. It appears under helloworld. Gõ hello.py rồi nhấn Enter. Tệp hiện ra bên dưới helloworld.
  4. Type this into the file: Gõ nội dung này vào tệp:
    python
    print("Hello")
  5. Press Ctrl+S to save. Nhấn Ctrl+S để lưu.

0.6 — Open Git Bash in your folder

  1. Close any Git Bash window that is already open. Đóng mọi cửa sổ Git Bash đang mở.
  2. In File Explorer, open (D:) → your folder → helloworld. Trong File Explorer, mở (D:) → thư mục của bạn → helloworld.
  3. Right-click an empty space → Open Git Bash here. (No option? Click "Show more options" first.) Bấm chuột phải vào chỗ trống → Open Git Bash here. (Không thấy? Bấm "Show more options" trước.)
  4. Type ls and press Enter. Gõ ls rồi nhấn Enter.
    bash
    ls
  5. You should see hello.py. Bạn sẽ thấy hello.py.

0.7 — Run your first file

  1. Type this and press Enter: Gõ dòng này rồi nhấn Enter:
    bash
    python hello.py
  2. You should see Hello. Your computer is ready. Bạn sẽ thấy Hello. Máy tính đã sẵn sàng.

🎯 Section 1 — The Problem

A class has 100 students. Each one has a score. Your job: print the scores from lowest to highest. Một lớp có 100 học sinh, mỗi bạn có một điểm. Nhiệm vụ: in điểm từ thấp đến cao.

The scores look like this — one number per line, 100 lines in total: Điểm có dạng như sau — mỗi dòng một số, tổng cộng 100 dòng:

87
92
78
95
85
...

You found it: typing 100 numbers every single time you test is impossible. Before we can sort anything, we need the data to come from somewhere else. Bạn đã thấy: gõ 100 số mỗi lần chạy thử là không thể. Trước khi sắp xếp, dữ liệu phải đến từ nơi khác.

📂 Section 2 — Read the Scores From a File

The 100 numbers are already in a text file called scores.txt. Your program can read them from the file, so you never type them again. 100 số đã có sẵn trong tệp văn bản scores.txt. Chương trình của bạn đọc chúng từ tệp, nên bạn không phải gõ lại nữa.

python
scores = [] with open("scores.txt") as f: for line in f: scores.append(int(line)) for s in scores: print(s)

🔢 Section 3 — Sort Them

The scores are in a list. Python can put a list in order with one line. Điểm đang nằm trong một list. Python sắp xếp list chỉ bằng một dòng.

python
scores = [] with open("scores.txt") as f: for line in f: scores.append(int(line)) scores.sort() for s in scores: print(s)

scores.sort() rearranges the list itself, from smallest to largest. sort() sắp xếp lại chính list đó, từ nhỏ đến lớn.

Watch sort() / Xem sort() chạy
87
92
78
95
85
Screen
After reading the file, scores holds the numbers in file order. Here is one way scores.sort() can put them in order — two numbers at a time. Sau khi đọc tệp, scores chứa các số theo thứ tự trong tệp. Đây là một cách scores.sort() sắp xếp chúng — mỗi lần hai số.
1 / 19

💾 Section 4 — Write the Answer to a File

Printing 100 lines to the screen scrolls away. Write the answer into out.txt instead, so you can open it and check it. When you run this program, it shows nothing on the screen — that is normal. It creates out.txt in your helloworld folder; open it in VS Code to see the answer. In 100 dòng ra màn hình sẽ bị trôi mất. Hãy ghi kết quả vào tệp out.txt để mở ra kiểm tra. Khi chạy, chương trình không hiện gì trên màn hình — như vậy là bình thường. Nó tạo tệp out.txt trong thư mục helloworld; mở tệp đó trong VS Code để xem kết quả.

python
scores = [] with open("scores.txt") as f: for line in f: scores.append(int(line)) scores.sort() with open("out.txt", "w") as f: for s in scores: f.write(str(s) + "\n")

🔄 Section 5 — New Requirement: Best Student at the Top

Now the scores must go from highest to lowest. Bây giờ điểm phải xếp từ cao xuống thấp.

With nothing inside its brackets, sort() always puts the smallest first. To get a different order, you have to tell it what to sort by — and you tell it with a function. Khi không có gì trong ngoặc, sort() luôn xếp nhỏ trước. Muốn thứ tự khác, bạn phải nói cho nó biết sắp xếp theo cái gì — bằng một hàm.

python
def highest_first(score): return -score scores = [] with open("scores.txt") as f: for line in f: scores.append(int(line)) scores.sort(key=highest_first) with open("out.txt", "w") as f: for s in scores: f.write(str(s) + "\n")

Compared with Section 4, two things are new: the def highest_first at the top, and the sort line is now scores.sort(key=highest_first). Write highest_first with no brackets: you are handing the function to sort, and sort calls it for you. So với Phần 4, có hai chỗ mới: hàm def highest_first ở đầu, và dòng sort giờ là scores.sort(key=highest_first). Viết highest_first không có dấu ngoặc: bạn đưa hàm cho sort, và sort sẽ tự gọi nó.

Read it like this: sort calls your function once for every score, and then sorts by whatever your function gave back. Your function hands back -score, so 95 becomes -95 and 78 becomes -78. Since -95 is smaller than -78, the 95 now comes first. Hiểu thế này: sort gọi hàm của bạn một lần cho mỗi điểm, rồi sắp xếp theo giá trị hàm trả về. Hàm trả về -score, nên 95 thành -95 và 78 thành -78. Vì -95 nhỏ hơn -78 nên 95 đứng trước.

Watch sort use key= / Xem sort dùng key=
87
92
78
95
85
scores in file order. Watch what sort(key=highest_first) does. scores theo thứ tự trong tệp. Xem sort(key=highest_first) làm gì.
1 / 22

🙋 Section 6 — New Requirement: Whose Score Is It?

A list of numbers is not very useful. The teacher wants to know which student got each score. So the data file changes — every line now has a name and a score, for example: Danh sách toàn số thì chưa dùng được. Thầy muốn biết điểm đó là của ai. Vì vậy tệp dữ liệu thay đổi — mỗi dòng có tên và điểm, ví dụ:

An 87
Binh 92
Chi 78
Dung 95
Em 85

Reading a line now gives you two things instead of one. split() cuts the line wherever there is a space: Đọc một dòng bây giờ cho bạn hai thứ. split() cắt dòng tại khoảng trắng:

python
with open("students.txt") as f: for line in f: name, score = line.split() score = int(score) print(name, score)

🧩 Section 7 — Keep the Name and the Score Together

The last requirement: write the students from the lowest score to the highest, each name still next to its score. Yêu cầu cuối: ghi học sinh từ điểm thấp nhất đến cao nhất, tên vẫn nằm cạnh điểm.

Here is a way that works. It uses what you already know — reading, sorting with key=, writing — plus one new idea. Đây là một cách làm đúng. Nó dùng những gì bạn đã biết — đọc tệp, sắp xếp bằng key=, ghi tệp — thêm một ý mới.

Instead of putting a number in the list, put a pair of things in the list. In Python a pair like this is called a tuple, and you write it with round brackets: Thay vì bỏ một số vào list, hãy bỏ vào một cặp. Trong Python cặp này gọi là tuple, viết bằng dấu ngoặc tròn:

python
data.append((name, int(score)))

Notice the two sets of round brackets: the outer ones belong to append, and the inner ones make the tuple. Để ý có hai lớp ngoặc tròn: lớp ngoài là của append, lớp trong tạo ra tuple.

The name comes first and the score second — the same order as the line in the file. To sort by the score, use key= exactly like in section 5: write a function that takes one tuple and gives back its score. Tên đứng trước, điểm đứng sau — đúng thứ tự như dòng trong tệp. Muốn sắp xếp theo điểm, dùng key= y như phần 5: viết một hàm nhận một tuple và trả về điểm của nó.

python
def by_score(student): return student[1]

student is one tuple, like ("Cong", 53). A tuple counts its parts from 0, like a list, so student[1] is the second part — the score. student là một tuple, ví dụ ("Cong", 53). Tuple đánh số các phần từ 0 giống list, nên student[1] là phần thứ hai — điểm.

The whole program: Toàn bộ chương trình:

python
def by_score(student): return student[1] data = [] with open("students.txt") as f: for line in f: name, score = line.split() data.append((name, int(score))) data.sort(key=by_score) with open("out.txt", "w") as f: for name, score in data: f.write(name + " " + str(score) + "\n")

Just like in section 5, sort calls by_score once for every tuple and sorts by what it gives back — the score. Each tuple moves as one piece, so the name is carried along with its score. Giống phần 5, sort gọi by_score một lần cho mỗi tuple và sắp xếp theo giá trị hàm trả về — điểm. Mỗi tuple di chuyển như một khối, nên tên luôn đi cùng điểm của mình.

Watch sort use by_score / Xem sort dùng by_score
Tuyet60
Cong53
Hai67
Loan90
Khai95
out.txt
Each line of students-5.txt became one tuple, name first — the same order as the file: ("Tuyet", 60), ("Cong", 53), … Mỗi dòng của students-5.txt thành một tuple, tên đứng trước — đúng thứ tự trong tệp.
1 / 17

🔍 Section 8 — What Actually Changed

Put the section 5 program and the section 7 program next to each other: Đặt chương trình phần 5 và phần 7 cạnh nhau:

Watch what changed / Xem phần nào thay đổi
Section 5 / Phần 5Section 7 / Phần 7
def highest_first(score):
return -score
def by_score(student):
return student[1]
scores = []
data = []
with open("scores.txt") as f:
for line in f:
scores.append(int(line))
with open("students.txt") as f:
for line in f:
name, score = line.split()
data.append((name, int(score)))
scores.sort(key=highest_first)
data.sort(key=by_score)
with open("out.txt", "w") as f:
for s in scores:
f.write(str(s) + "\n")
with open("out.txt", "w") as f:
for name, score in data:
f.write(name + " " + str(score) + "\n")
Changed / Có thay đổiNot changed / Không đổi
Your section 5 program sorted scores, best first. Your section 7 program sorts names together with their scores. Go through them one job at a time: what did the new requirement really change? Chương trình phần 5 sắp xếp điểm, cao nhất trước. Chương trình phần 7 sắp xếp tên cùng với điểm. Xem từng việc một: yêu cầu mới thật ra đã thay đổi những gì?
1 / 7

The requirement that looked like it broke everything never touched the sort line. To sort by something else, you change the small key function, not the sort — that is why key= is the real tool. And when each part of a program does one job, a change usually hits some parts and misses others. Yêu cầu tưởng như phá vỡ mọi thứ lại không đụng đến dòng sort. Muốn sắp xếp theo thứ khác, bạn chỉ đổi hàm key nhỏ, không đổi sort — vì vậy key= là công cụ thật. Và khi mỗi phần của chương trình chỉ làm một việc, một thay đổi thường chỉ ảnh hưởng vài phần.

✏️ Section 9 — Exercises

Every exercise has its own input file. Click the file name next to the question, drag the file from Downloads into your helloworld folder, and use that file name in your program — for exercise 1, ex1.txt. Exercises 1–4 have one score per line; exercises 5–11 have a name and a score. Mỗi bài tập có tệp dữ liệu riêng. Bấm vào tên tệp cạnh câu hỏi, kéo tệp từ Downloads vào thư mục helloworld, và dùng đúng tên tệp đó trong chương trình — với câu 1 là ex1.txt. Câu 1–4 mỗi dòng một điểm; câu 5–11 mỗi dòng một tên và một điểm.