Programming Fundamentals
Variables and Data Types
Understand variables, constants, and the fundamental data types used in programming — integers, floats, strings, and booleans.
Variables and Data Types
What is a Variable?
A variable is a named storage location in memory that holds a value which can change during program execution. Every variable has three key attributes: a name (identifier), a value (the data stored), and a type (the kind of data). Think of a variable as a labeled box — you can put something inside, look at it, and replace it with something else.
Naming Rules for Variables
- Must start with a letter or an underscore — not a digit.
- Can contain letters, digits, and underscores — no spaces or special characters.
- Cannot use reserved keywords such as if, for, while, return, or class.
- Names are case-sensitive: age, Age, and AGE are three different variables.
- Use descriptive names: user_age is far clearer than a or x1.
Assignment
The = operator assigns a value to a variable. This is not a mathematical equality — it is an instruction to store a value. Example: item_count = 25 stores the integer 25 in a variable named item_count. Example: status_label = "Ready" stores the string Ready. Example: unit_price = 9.99 stores a float. The variable on the left receives whatever value is on the right.
Integer (int)
Integers are whole numbers with no decimal point — positive, negative, or zero. Examples: 0, 42, -7, 1000000. Used for counting items, loop counters, and array indices. Python supports arbitrarily large integers; Java's int is 32-bit.
Float (floating-point)
Floats represent numbers with a decimal point. Examples: 3.14, -2.5, 0.001. Used for measurements and scientific calculations. Important caveat: 0.1 + 0.2 may not equal exactly 0.3 due to binary representation limits — use the decimal module for financial work.
String (str)
A string is a sequence of characters enclosed in quotes. Examples: "Hello, World!", 'Python', "user@email.com". The string "42" is text, not a number. An empty string "" is valid and has zero characters. Strings are immutable in Python — operations return new strings rather than modifying the original.
Boolean (bool)
Booleans have exactly two values: True or False (capitalized in Python). They are the result of comparisons and logical expressions. Examples: is_active = True, has_permission = False. In many languages, 0, empty string, and None are treated as False (falsy), while non-zero and non-empty values are True (truthy).
NoneType / null
Represents the deliberate absence of a value. Python uses None, Java and JavaScript use null, and JavaScript also has undefined for declared-but-unassigned variables. Use None/null to signal "no result" or "missing data".
Type Checking and Conversion
Use type(x) in Python or typeof x in JavaScript to find a variable's type. Type conversion (casting) changes a value to another type: int("42") converts string to integer 42, str(100) converts integer to "100", float("3.14") gives 3.14. Attempting int("hello") raises a ValueError — always validate input before converting.
Constants
A constant is a variable whose value should never change after initial assignment. Convention: name in ALL_CAPS. Examples: MAX_SIZE = 100, PI = 3.14159, BASE_URL = "https://api.example.com". Python has no enforcement; Java uses final; JavaScript uses const.
Arithmetic Operators
| Operator | Name | Example | Result | Use case |
|---|---|---|---|---|
+ | Addition | 7 + 3 | 10 | Add two numeric values. |
- | Subtraction | 7 - 3 | 4 | Find the difference between two values. |
* | Multiplication | 7 * 3 | 21 | Scale or repeat numeric quantities. |
/ | Division | 10 / 4 | 2.5 | Always returns a float in Python 3. |
// | Floor division | 10 // 4 | 2 | Divide and round down to the nearest whole number. |
% | Modulo | 10 % 3 | 1 | Get the remainder after division. |
** | Exponentiation | 2 ** 8 | 256 | Raise a number to a power. |
| Term | Meaning |
|---|---|
| total | 7 + 3 |
| average | 10 / 4 |
| whole_groups | 10 // 4 |
| leftover | 10 % 3 |
| bytes_count | 2 ** 8 |
Comparison and Assignment Operators
Comparison operators test a relationship and return a Boolean value: True or False. Assignment operators store or update a value in a variable.
| Group | Operator | Meaning | Example |
|---|---|---|---|
| Comparison | == | Equal to | score == 100 |
| Comparison | != | Not equal to | status != "closed" |
| Comparison | < | Less than | age < 18 |
| Comparison | > | Greater than | price > 0 |
| Comparison | <= | Less than or equal to | attempts <= 3 |
| Comparison | >= | Greater than or equal to | score >= 50 |
| Assignment | = | Assign a value | count = 10 |
| Assignment | += | Add and assign | count += 1 |
| Assignment | -= | Subtract and assign | stock -= sold |
| Assignment | *= | Multiply and assign | price *= 1.1 |
score = 72
passed = score >= 50
score += 5String Operations
| Operation | Python example | Result | Note |
|---|---|---|---|
| Concatenation | "Hello" + " " + "World" | "Hello World" | Joins strings together. |
| Length | len("hello") | 5 | JavaScript uses s.length. |
| Indexing | "hello"[0] | "h" | Indexes start at 0. |
| Last character | "hello"[4] | "o" | The final index is length minus 1. |
| Term | Meaning |
|---|---|
| message | "Hello" + " " + "World" |
| text_length | len(message) |
| first_letter | message[0] |
| last_letter | message[10] |
Variable Scope
| Scope | Where it is created | Where it can be used | Best practice |
|---|---|---|---|
| Local variable | Inside a function | Only inside that function | Use local variables for temporary work inside one task. |
| Global variable | At the top level of a file | Across the module after it is defined | Avoid changing globals from many places; pass values through parameters instead. |
tax_rate = 0.1
def calculate_total(price):
tax = price * tax_rate
return price + taxIn this example, tax_rate is global because it is defined outside the function. price and tax are local because they exist only while calculate_total runs.
Memory and References
In Python, a variable is a reference (pointer) to an object in memory. When you write a = b, both point to the same object. For mutable types like lists, modifying the object through one variable affects all references to it — an important source of subtle bugs for beginners.
Biến và Kiểu Dữ liệu
Biến là gì?
Biến là một vùng lưu trữ có tên trong bộ nhớ, dùng để giữ một giá trị có thể thay đổi trong lúc chương trình chạy. Mỗi biến có ba thuộc tính chính: tên (định danh), giá trị (dữ liệu đang được lưu), và kiểu dữ liệu (loại dữ liệu). Có thể hình dung biến như một chiếc hộp có nhãn: bạn có thể đặt dữ liệu vào, đọc dữ liệu ra, rồi thay dữ liệu đó bằng giá trị khác.
Quy tắc đặt tên biến
- Phải bắt đầu bằng chữ cái hoặc dấu gạch dưới; không được bắt đầu bằng chữ số.
- Có thể chứa chữ cái, chữ số và dấu gạch dưới; không dùng khoảng trắng hoặc ký tự đặc biệt.
- Không được dùng từ khóa dành riêng như if, for, while, return, hoặc class.
- Tên biến phân biệt chữ hoa và chữ thường: age, Age, và AGE là ba biến khác nhau.
- Nên dùng tên rõ nghĩa: user_age dễ hiểu hơn nhiều so với a hoặc x1.
Phép gán
Toán tử = gán một giá trị cho biến. Đây không phải dấu bằng trong toán học; đây là lệnh yêu cầu chương trình lưu giá trị bên phải vào biến bên trái. Ví dụ: item_count = 25 lưu số nguyên 25 vào biến item_count. Ví dụ: status_label = "Ready" lưu chuỗi Ready. Ví dụ: unit_price = 9.99 lưu một số thực. Biến ở bên trái nhận giá trị được tạo ra ở bên phải.
Số nguyên (int)
Số nguyên là các số không có phần thập phân: có thể là số dương, số âm hoặc số 0. Ví dụ: 0, 42, -7, 1000000. Số nguyên thường dùng để đếm số lượng, làm biến đếm trong vòng lặp, hoặc làm chỉ số của mảng/danh sách. Python hỗ trợ số nguyên rất lớn; trong Java, kiểu int thường là số nguyên 32-bit.
Số thực dấu phẩy động (float)
Float biểu diễn các số có phần thập phân. Ví dụ: 3.14, -2.5, 0.001. Float thường dùng cho phép đo lường và tính toán khoa học. Lưu ý quan trọng: 0.1 + 0.2 có thể không đúng chính xác bằng 0.3 do giới hạn biểu diễn nhị phân; với bài toán tài chính, nên dùng module decimal.
Chuỗi (str)
Chuỗi là một dãy ký tự được đặt trong dấu nháy. Ví dụ: "Hello, World!", 'Python', "user@email.com". Chuỗi "42" là văn bản, không phải số. Chuỗi rỗng "" vẫn hợp lệ và có độ dài bằng 0. Trong Python, chuỗi là immutable, nghĩa là các thao tác trên chuỗi tạo ra chuỗi mới thay vì sửa trực tiếp chuỗi ban đầu.
Boolean (bool)
Boolean chỉ có đúng hai giá trị: True hoặc False (viết hoa chữ cái đầu trong Python). Boolean là kết quả của phép so sánh và biểu thức logic. Ví dụ: is_active = True, has_permission = False. Trong nhiều ngôn ngữ, 0, chuỗi rỗng và None được xem là False (falsy), còn giá trị khác 0 và chuỗi không rỗng được xem là True (truthy).
NoneType / null
Biểu diễn việc cố ý không có giá trị. Python dùng None, Java và JavaScript dùng null, còn JavaScript còn có undefined cho biến đã khai báo nhưng chưa được gán giá trị. Dùng None/null để biểu thị "không có kết quả" hoặc "dữ liệu bị thiếu".
Kiểm tra kiểu và chuyển đổi kiểu
Dùng type(x) trong Python hoặc typeof x trong JavaScript để kiểm tra kiểu dữ liệu của biến. Chuyển đổi kiểu (casting) biến một giá trị sang kiểu khác: int("42") chuyển chuỗi thành số nguyên 42, str(100) chuyển số nguyên thành "100", float("3.14") tạo ra 3.14. Nếu chạy int("hello"), Python sẽ báo ValueError; vì vậy cần kiểm tra dữ liệu đầu vào trước khi chuyển kiểu.
Hằng số
Hằng số là biến có giá trị không nên thay đổi sau khi được gán lần đầu. Quy ước thường dùng: viết tên bằng chữ in hoa. Ví dụ: MAX_SIZE = 100, PI = 3.14159, BASE_URL = "https://api.example.com". Python không cưỡng chế hằng số ở mức ngôn ngữ; Java dùng final; JavaScript dùng const.
Toán tử số học
| Toán tử | Tên | Ví dụ | Kết quả | Khi dùng |
|---|---|---|---|---|
+ | Cộng | 7 + 3 | 10 | Cộng hai giá trị số. |
- | Trừ | 7 - 3 | 4 | Tìm hiệu giữa hai giá trị. |
* | Nhân | 7 * 3 | 21 | Nhân hoặc phóng đại một đại lượng. |
/ | Chia | 10 / 4 | 2.5 | Trong Python 3, luôn trả về float. |
// | Chia lấy phần nguyên | 10 // 4 | 2 | Chia rồi làm tròn xuống số nguyên gần nhất. |
% | Modulo | 10 % 3 | 1 | Lấy phần dư sau phép chia. |
** | Lũy thừa | 2 ** 8 | 256 | Nâng một số lên một số mũ. |
| Term | Meaning |
|---|---|
| total | 7 + 3 |
| average | 10 / 4 |
| whole_groups | 10 // 4 |
| leftover | 10 % 3 |
| bytes_count | 2 ** 8 |
Toán tử so sánh và phép gán
Toán tử so sánh kiểm tra mối quan hệ giữa hai giá trị và trả về Boolean: True hoặc False. Toán tử gán dùng để lưu hoặc cập nhật giá trị trong biến.
| Nhóm | Toán tử | Ý nghĩa | Ví dụ |
|---|---|---|---|
| So sánh | == | Bằng | score == 100 |
| So sánh | != | Không bằng | status != "closed" |
| So sánh | < | Nhỏ hơn | age < 18 |
| So sánh | > | Lớn hơn | price > 0 |
| So sánh | <= | Nhỏ hơn hoặc bằng | attempts <= 3 |
| So sánh | >= | Lớn hơn hoặc bằng | score >= 50 |
| Gán | = | Gán giá trị | count = 10 |
| Gán | += | Cộng rồi gán lại | count += 1 |
| Gán | -= | Trừ rồi gán lại | stock -= sold |
| Gán | *= | Nhân rồi gán lại | price *= 1.1 |
score = 72
passed = score >= 50
score += 5Thao tác chuỗi
| Thao tác | Ví dụ Python | Kết quả | Ghi chú |
|---|---|---|---|
| Nối chuỗi | "Hello" + " " + "World" | "Hello World" | Ghép các chuỗi lại với nhau. |
| Độ dài | len("hello") | 5 | JavaScript dùng s.length. |
| Truy cập bằng chỉ số | "hello"[0] | "h" | Chỉ số bắt đầu từ 0. |
| Ký tự cuối | "hello"[4] | "o" | Chỉ số cuối cùng bằng độ dài trừ 1. |
| Term | Meaning |
|---|---|
| message | "Hello" + " " + "World" |
| text_length | len(message) |
| first_letter | message[0] |
| last_letter | message[10] |
Phạm vi biến
| Phạm vi | Nơi tạo ra | Nơi có thể dùng | Thực hành tốt |
|---|---|---|---|
| Biến cục bộ | Bên trong một hàm | Chỉ dùng được bên trong hàm đó | Dùng biến cục bộ cho dữ liệu tạm trong một tác vụ. |
| Biến toàn cục | Ở cấp cao nhất của file | Có thể dùng trong module sau khi được định nghĩa | Tránh sửa biến toàn cục từ nhiều nơi; nên truyền giá trị qua tham số. |
tax_rate = 0.1
def calculate_total(price):
tax = price * tax_rate
return price + taxTrong ví dụ này, tax_rate là biến toàn cục vì được định nghĩa bên ngoài hàm. price và tax là biến cục bộ vì chỉ tồn tại trong lúc calculate_total chạy.
Bộ nhớ và tham chiếu
Trong Python, biến là một tham chiếu (pointer) đến một đối tượng trong bộ nhớ. Khi viết a = b, cả hai biến cùng trỏ đến cùng một đối tượng. Với kiểu dữ liệu mutable như list, nếu sửa đối tượng thông qua một biến thì mọi tham chiếu khác đến đối tượng đó cũng thấy thay đổi; đây là nguồn gây lỗi khá tinh vi với người mới học.