Study Web

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

OperatorNameExampleResultUse case
+Addition7 + 310Add two numeric values.
-Subtraction7 - 34Find the difference between two values.
*Multiplication7 * 321Scale or repeat numeric quantities.
/Division10 / 42.5Always returns a float in Python 3.
//Floor division10 // 42Divide and round down to the nearest whole number.
%Modulo10 % 31Get the remainder after division.
**Exponentiation2 ** 8256Raise a number to a power.
TermMeaning
total7 + 3
average10 / 4
whole_groups10 // 4
leftover10 % 3
bytes_count2 ** 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.

GroupOperatorMeaningExample
Comparison==Equal toscore == 100
Comparison!=Not equal tostatus != "closed"
Comparison<Less thanage < 18
Comparison>Greater thanprice > 0
Comparison<=Less than or equal toattempts <= 3
Comparison>=Greater than or equal toscore >= 50
Assignment=Assign a valuecount = 10
Assignment+=Add and assigncount += 1
Assignment-=Subtract and assignstock -= sold
Assignment*=Multiply and assignprice *= 1.1
score = 72
passed = score >= 50
score += 5

String Operations

OperationPython exampleResultNote
Concatenation"Hello" + " " + "World""Hello World"Joins strings together.
Lengthlen("hello")5JavaScript uses s.length.
Indexing"hello"[0]"h"Indexes start at 0.
Last character"hello"[4]"o"The final index is length minus 1.
TermMeaning
message"Hello" + " " + "World"
text_lengthlen(message)
first_lettermessage[0]
last_lettermessage[10]

Variable Scope

ScopeWhere it is createdWhere it can be usedBest practice
Local variableInside a functionOnly inside that functionUse local variables for temporary work inside one task.
Global variableAt the top level of a fileAcross the module after it is definedAvoid changing globals from many places; pass values through parameters instead.
tax_rate = 0.1

def calculate_total(price):
    tax = price * tax_rate
    return price + tax

In 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ênVí dụKết quảKhi dùng
+Cộng7 + 310Cộng hai giá trị số.
-Trừ7 - 34Tìm hiệu giữa hai giá trị.
*Nhân7 * 321Nhân hoặc phóng đại một đại lượng.
/Chia10 / 42.5Trong Python 3, luôn trả về float.
//Chia lấy phần nguyên10 // 42Chia rồi làm tròn xuống số nguyên gần nhất.
%Modulo10 % 31Lấy phần dư sau phép chia.
**Lũy thừa2 ** 8256Nâng một số lên một số mũ.
TermMeaning
total7 + 3
average10 / 4
whole_groups10 // 4
leftover10 % 3
bytes_count2 ** 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ómToán tửÝ nghĩaVí dụ
So sánh==Bằngscore == 100
So sánh!=Không bằngstatus != "closed"
So sánh<Nhỏ hơnage < 18
So sánh>Lớn hơnprice > 0
So sánh<=Nhỏ hơn hoặc bằngattempts <= 3
So sánh>=Lớn hơn hoặc bằngscore >= 50
Gán=Gán giá trịcount = 10
Gán+=Cộng rồi gán lạicount += 1
Gán-=Trừ rồi gán lạistock -= sold
Gán*=Nhân rồi gán lạiprice *= 1.1
score = 72
passed = score >= 50
score += 5

Thao tác chuỗi

Thao tácVí dụ PythonKết quảGhi chú
Nối chuỗi"Hello" + " " + "World""Hello World"Ghép các chuỗi lại với nhau.
Độ dàilen("hello")5JavaScript 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.
TermMeaning
message"Hello" + " " + "World"
text_lengthlen(message)
first_lettermessage[0]
last_lettermessage[10]

Phạm vi biến

Phạm viNơi tạo raNơi có thể dùngThực hành tốt
Biến cục bộBên trong một hàmChỉ 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 fileCó thể dùng trong module sau khi được định nghĩaTrá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 + tax

Trong ví dụ này, tax_rate là biến toàn cục vì được định nghĩa bên ngoài hàm. pricetax 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.