Data Structures & Strings

You already know lists. Now let us meet the rest of the collection family — tuples and dictionaries — and learn strings as text you can index, search, and format. Bạn đã biết danh sách (list). Bây giờ hãy gặp phần còn lại của gia đình collection — tuple và dictionary — và học chuỗi (string).

📘 Section 1 — The Collection Family

A list stores many values in order and can be changed. Python has more collections for different jobs. Một list lưu nhiều giá trị theo thứ tự và có thể thay đổi. Python còn có các collection khác cho từng mục đích.

📦 Section 2 — Tuples (Bộ giá trị)

A tuple is like a list, but it cannot be changed after you create it. Use it for data that should stay fixed. Tuple giống list nhưng không thể thay đổi sau khi tạo. Dùng cho dữ liệu cần giữ cố định.

python
# Create with parentheses point = (3, 5) colors = ("red", "green", "blue") # Access by index — just like a list print(point[0]) # 3 print(colors[-1]) # blue

Tuples cannot change / Không thể thay đổi

python
point = (3, 5) point[0] = 10 # ❌ TypeError: tuples cannot be changed

Unpacking / Giải nén

You can split a tuple into separate variables in one line. Bạn có thể tách một tuple thành các biến riêng trong một dòng.

python
point = (3, 5) x, y = point print(x) # 3 print(y) # 5 # A common trick: swap two values a, b = 1, 2 a, b = b, a print(a, b) # 2 1

🗂️ Section 3 — Dictionaries (Từ điển)

A dictionary stores key → value pairs, like a real dictionary maps a word to its meaning. Dictionary lưu các cặp khóa → giá trị, giống từ điển ánh xạ một từ tới nghĩa của nó.

python
# key : value ages = {"Alice": 14, "Bob": 15} # Access by key print(ages["Alice"]) # 14 # Add or update ages["Charlie"] = 13 # add new ages["Alice"] = 15 # update existing # Remove del ages["Bob"]

Check keys with in / Kiểm tra khóa với in

python
ages = {"Alice": 14, "Bob": 15} print("Alice" in ages) # True print("Dan" in ages) # False

Looping over a dictionary / Duyệt từ điển

python
ages = {"Alice": 14, "Bob": 15} for name in ages: # keys print(name, ages[name]) for name, age in ages.items(): # key and value print(f"{name} is {age}") print(len(ages)) # 2 — number of pairs

🔤 Section 4 — Strings as Sequences

A string is a sequence of characters, so you can index and slice it just like a list. Chuỗi là một dãy ký tự, nên bạn có thể truy cập và cắt lát như với list.

python
word = "Python" print(word[0]) # P (first character) print(word[-1]) # n (last character) print(word[0:3]) # Pyt (slice: index 0,1,2) print(len(word)) # 6 (length)

Join and repeat / Nối và lặp

python
first = "Hello" second = "World" print(first + " " + second) # Hello World (concatenation) print("ha" * 3) # hahaha (repetition)

Loop and search / Duyệt và tìm kiếm

python
word = "banana" for letter in word: # go through each character print(letter) print("an" in word) # True — substring check

🛠️ Section 5 — String Methods

Strings have many built-in methods. Because strings are immutable, these methods return a new string — the original does not change. Chuỗi có nhiều phương thức sẵn có. Vì chuỗi bất biến, các phương thức trả về chuỗi mới — chuỗi gốc không đổi.

python
text = " Hello World " print(text.upper()) # " HELLO WORLD " print(text.lower()) # " hello world " print(text.strip()) # "Hello World" (remove edge spaces) print(text.replace("o", "0")) # " Hell0 W0rld " print("Hello World".find("World")) # 6 (position, or -1 if missing) print("a,b,c".split(",")) # ['a', 'b', 'c'] print("-".join(["2026", "07", "24"])) # "2026-07-24" print("banana".count("a")) # 3

✨ Section 6 — f-strings (Định dạng chuỗi)

An f-string lets you put variables directly inside a string. Start the string with f and wrap values in { }. f-string cho phép đặt biến trực tiếp trong chuỗi. Bắt đầu bằng f và đặt giá trị trong dấu ngoặc nhọn.

python
name = "Linh" age = 14 print(f"Hello {name}, you are {age} years old.") # Hello Linh, you are 14 years old. # Format numbers: .1f means 1 decimal place avg = 80.6666 print(f"Average = {avg:.1f}") # Average = 80.7

🧩 Section 7 — Putting It Together

Let us count how many times each word appears in a sentence — using a dictionary, split, and a loop together. Hãy đếm số lần mỗi từ xuất hiện trong một câu — dùng dictionary, split và vòng lặp cùng nhau.

python
sentence = input("Enter a sentence: ") words = sentence.split(" ") counts = {} for word in words: if word in counts: counts[word] = counts[word] + 1 else: counts[word] = 1 for word, n in counts.items(): print(f"{word}: {n}")

Example / Ví dụ:

Enter a sentence: the cat sat on the mat
the: 2
cat: 1
sat: 1
on: 1
mat: 1

📝 Section 8 — Practice Exercises

Exercise 1 — Rabbit Pairs

A farm has 1 pair of rabbits in month 1 and 1 pair in month 2. From month 3 on, the number of pairs each month is the two previous months added together. Read N and print how many pairs there are in month N. Trang trại có 1 cặp thỏ ở tháng 1 và 1 cặp ở tháng 2. Từ tháng 3, số cặp mỗi tháng bằng tổng hai tháng liền trước. Nhập N và in số cặp thỏ ở tháng N.

Example Input:

6

Example Output:

8

Exercise 2 — Build a Dictionary

Read 3 names and their ages, store them in a dictionary, then look one up by name. Đọc 3 tên và tuổi, lưu vào dictionary, rồi tra cứu một tên bất kỳ.

Example Input:

Alice 14
Bob 15
Chi 13
Bob

Example Output:

Bob: 15

Exercise 3 — Word Count

Count how many times each word appears in a sentence. Đếm số lần mỗi từ xuất hiện trong một câu.

Example Input:

the cat sat on the mat

Example Output:

the: 2
cat: 1
sat: 1
on: 1
mat: 1

Exercise 4 — Reverse a String

Read a word and print it backwards using slicing ([::-1]). Đọc một từ và in ngược lại bằng slicing.

Example Input:

Python

Example Output:

nohtyP

Exercise 5 — Count Vowels

Count the vowels (a, e, i, o, u) in a string using a loop. Đếm số nguyên âm trong một chuỗi bằng vòng lặp.

Example Input:

programming is fun

Example Output:

5

Exercise 6 — Clean a Name

Read a name that may have extra spaces; print it stripped and in Title Case. Đọc một tên có thể thừa khoảng trắng; in ra sau khi bỏ khoảng trắng và viết hoa chữ đầu.

Example Input:

   linh nguyen   

Example Output:

Linh Nguyen

Exercise 7 — Split Fields

Read a comma-separated line and print each field on its own line. Đọc một dòng ngăn cách bằng dấu phẩy và in từng phần một dòng.

Example Input:

apple,banana,cherry

Example Output:

apple
banana
cherry

Exercise 8 — Receipt Line

Read an item name and a price; print a receipt line like Apple .... $3.50, with the price showing exactly 2 decimal places. Đọc tên món và giá; in một dòng hóa đơn với giá có đúng 2 chữ số thập phân.

Example Input:

Apple
3.5

Example Output:

Apple .... $3.50

🚀 Section 9 — Challenge: Contact Book

Build a small contact book using a dictionary of name → phone number. Xây một sổ danh bạ nhỏ dùng dictionary tên → số điện thoại.

Example Output:

add / find / list / quit: add
Name: Minh
Phone: 0987654321
add / find / list / quit: add
Name: Linh
Phone: 0901234567
add / find / list / quit: find
Name: Linh
Linh: 0901234567
add / find / list / quit: find
Name: Nam
Not found
add / find / list / quit: list
Minh: 0987654321
Linh: 0901234567
add / find / list / quit: quit
python
contacts = {} while True: action = input("add / find / list / quit: ") if action == "add": name = input("Name: ") phone = input("Phone: ") contacts[name] = phone elif action == "find": name = input("Name: ") if name in contacts: print(f"{name}: {contacts[name]}") else: print("Not found") elif action == "list": for name, phone in contacts.items(): print(f"{name}: {phone}") elif action == "quit": break

Summary / Tóm tắt