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 ExplorerDownloads → 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 ExplorerDownloads → 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 ExplorerDownloads → 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 ExplorerThis 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 → NewFolder. 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 folderOpen 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 folderhelloworld. 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.

💾 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

The teacher changes her mind. She wants the scores from highest to lowest now. Cô giáo đổi ý. Bây giờ cô muốn điểm 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.

🙋 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. Cô giáo 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, writing — with one change. Đâ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, ghi tệp — chỉ khác một chỗ.

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((score, name))

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 whole program: Toàn bộ chương trình:

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

When Python sorts tuples, it compares the first part first. The score is the first part, so the list comes out in score order — and the name is carried along, because the name and the score are one single value. Khi sắp xếp tuple, Python so sánh phần đầu tiên trước. Điểm là phần đầu, nên list được sắp theo điểm — và tên đi theo cùng, vì tên và điểm là một giá trị duy nhất.

🔍 Section 8 — What Actually Changed

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

The requirement that looked like it broke everything left the sorting completely alone. That happens 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 gì đến phần sắp xếp. Điều đó xảy ra 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–8 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–8 mỗi dòng một tên và một điểm.