Nội dung bài họcLesson content
Biến và kiểu dữ liệu trong PythonVariables and data types in Python
Python có 4 kiểu dữ liệu cơ bản: str (chuỗi văn bản), int (số nguyên), float (số thập phân), bool (đúng/sai). Biến không cần khai báo kiểu — Python tự nhận diện. Gán giá trị trực tiếp: ten = "An", tuoi = 16.Python has 4 basic data types: str (text string), int (integer), float (decimal), bool (true/false). Variables do not need type declarations — Python detects automatically. Assign directly: name = "An", age = 16.
f-string: ghép chuỗi và biếnf-strings: combining text and variables
f-string là cách hiện đại ghép biến vào chuỗi. Đặt f trước nháy và dùng {} để chèn biến: f"Tôi là {ten}". Cũng có thể tính toán bên trong: f"Tuổi năm sau: {tuoi + 1}". f-string dễ đọc hơn dấu phẩy hoặc +.f-strings are the modern way to embed variables in text. Put f before the quote and use {} to insert variables: f"I am {name}". You can also compute inside: f"Age next year: {age + 1}". f-strings are more readable than commas or +.
ten = "Hà Mi"
tuoi = 16
diem_tb = 9.5
thich_code = True
print(f"Xin chào! Tôi là {ten}.")
print(f"Tuổi / Age: {tuoi}")
print(f"Điểm TB / Avg: {diem_tb}")
print(f"Thích code: {thich_code}")
print(f"Kiểu của tuổi: {type(tuoi)}")
Kiểu bool và phép so sánhBoolean type and comparisons
bool chỉ có 2 giá trị: True hoặc False. Kết quả phép so sánh là bool: 5 > 3 → True, 5 < 3 → False. Dùng == để so sánh bằng, != để so sánh khác. bool quan trọng trong câu lệnh if.bool has only 2 values: True or False. Comparison results are bool: 5 > 3 → True, 5 < 3 → False. Use == for equality, != for inequality. bool is important in if statements.
x = 10
y = 20
print(x > y) # False
print(x < y) # True
print(x == 10) # True
print(x != 5) # True
print(type(x > y)) # <class 'bool'>
Chuyển đổi kiểu dữ liệuType conversion
Dùng int(), float(), str(), bool() để chuyển kiểu. Ví dụ: int("22") → 22 (chuỗi thành số), str(22) → "22" (số thành chuỗi). Cẩn thận: int("hello") sẽ lỗi vì "hello" không phải số.Use int(), float(), str(), bool() to convert types. Example: int("22") → 22 (string to number), str(22) → "22" (number to string). Caution: int("hello") will error because "hello" is not a number.
# Chuỗi thành số
tuoi_str = "22"
tuoi_int = int(tuoi_str)
print(tuoi_int + 1) # 23
# Số thành chuỗi
diem = 9.5
diem_str = str(diem)
print("Điểm: " + diem_str) # Điểm: 9.5
# Số thành float
print(float(5)) # 5.0
print(int(5.9)) # 5 (cắt phần thập phân)