Cú Pháp Python Cơ Bản
1. Variables (Biến)
1.1 Khai báo biến
Python không cần khai báo kiểu dữ liệu - tự động suy luận!
Python
1# Khai báo biến đơn giản2name = "MinAI" # String3age = 25 # Integer4price = 19.99 # Float5is_active = True # Boolean67# Multiple assignment8x, y, z = 1, 2, 39a = b = c = 01011# Swap values (Pythonic way!)12x, y = y, x1.2 Quy tắc đặt tên biến
Python
1# ✅ Hợp lệ2my_variable = 13myVariable = 2 # camelCase4MyVariable = 3 # PascalCase 5my_variable_2 = 46_private = 578# ❌ Không hợp lệ92variable = 1 # Bắt đầu bằng số10my-variable = 2 # Có dấu gạch ngang11my variable = 3 # Có khoảng trắng1.3 Convention trong Python (PEP 8)
| Loại | Convention | Ví dụ |
|---|---|---|
| Variable | snake_case | user_name |
| Constant | UPPER_SNAKE | MAX_SIZE |
| Function | snake_case | calculate_total() |
| Class | PascalCase | DataProcessor |
| Private | _prefix | _internal_var |
2. Data Types (Kiểu dữ liệu)
2.1 Primitive Types
Python
1# Integer - Số nguyên2count = 423big_num = 1_000_000 # Underscore cho dễ đọc45# Float - Số thực6pi = 3.141597scientific = 1.5e-10 # 1.5 × 10^-1089# String - Chuỗi10name = "Python"11message = 'Hello World'12multiline = """13This is a14multiline string15"""1617# Boolean18is_valid = True19is_empty = False2021# None - Giá trị null22result = None2.2 Kiểm tra kiểu dữ liệu
Python
1x = 422print(type(x)) # <class 'int'>3print(isinstance(x, int)) # True45# Kiểm tra nhiều kiểu6print(isinstance(x, (int, float))) # True2.3 Type Conversion
Python
1# String to Number2num_str = "42"3num_int = int(num_str) # 424num_float = float(num_str) # 42.056# Number to String7x = 1008s = str(x) # "100"910# Boolean conversion11bool(0) # False12bool(1) # True13bool("") # False14bool("text") # True15bool([]) # False16bool([1,2]) # True3. Operators (Toán tử)
3.1 Arithmetic Operators
Python
1a, b = 10, 323print(a + b) # 13 - Cộng4print(a - b) # 7 - Trừ5print(a * b) # 30 - Nhân6print(a / b) # 3.333... - Chia (float)7print(a // b) # 3 - Chia lấy phần nguyên8print(a % b) # 1 - Chia lấy dư9print(a ** b) # 1000 - Lũy thừa (10^3)3.2 Comparison Operators
Python
1x, y = 5, 1023print(x == y) # False - Bằng4print(x != y) # True - Khác5print(x < y) # True - Nhỏ hơn6print(x <= y) # True - Nhỏ hơn hoặc bằng7print(x > y) # False - Lớn hơn8print(x >= y) # False - Lớn hơn hoặc bằng910# Chained comparison (Pythonic!)11age = 2512print(18 <= age < 65) # True3.3 Logical Operators
Python
1a, b = True, False23print(a and b) # False4print(a or b) # True5print(not a) # False67# Short-circuit evaluation8x = 59result = x > 0 and x < 10 # True1011# Practical example12name = ""13display = name or "Anonymous" # "Anonymous"3.4 Assignment Operators
Python
1x = 102x += 5 # x = x + 5 → 153x -= 3 # x = x - 3 → 124x *= 2 # x = x * 2 → 245x /= 4 # x = x / 4 → 6.06x //= 2 # x = x // 2 → 3.07x **= 2 # x = x ** 2 → 9.04. Strings (Chuỗi)
4.1 String Operations
Python
1s = "Python Data Science"23# Indexing (0-based)4print(s[0]) # 'P'5print(s[-1]) # 'e' (từ cuối)67# Slicing [start:end:step]8print(s[0:6]) # 'Python'9print(s[7:]) # 'Data Science'10print(s[::-1]) # Đảo ngược chuỗi1112# Length13print(len(s)) # 194.2 String Methods
Python
1text = " Hello World "23# Case methods4text.lower() # " hello world "5text.upper() # " HELLO WORLD "6text.title() # " Hello World "7text.capitalize() # " hello world "89# Whitespace10text.strip() # "Hello World"11text.lstrip() # "Hello World "12text.rstrip() # " Hello World"1314# Find & Replace15text.find("World") # 8 (index)16text.replace("World", "Python") # " Hello Python "1718# Split & Join19"a,b,c".split(",") # ['a', 'b', 'c']20"-".join(['a','b','c']) # "a-b-c"2122# Check methods23"123".isdigit() # True24"abc".isalpha() # True25"abc123".isalnum() # True4.3 String Formatting
Python
1name = "MinAI"2price = 19.993quantity = 345# f-string (Python 3.6+) - Khuyến nghị!6print(f"Hello, {name}!")7print(f"Total: ${price * quantity:.2f}")89# Format specifiers10num = 1234.567811print(f"{num:.2f}") # 1234.57 (2 decimals)12print(f"{num:,.2f}") # 1,234.57 (with comma)13print(f"{num:10.2f}") # ' 1234.57' (width 10)14print(f"{num:>10.2f}") # ' 1234.57' (right align)15print(f"{num:<10.2f}") # '1234.57 ' (left align)1617# Percentage18ratio = 0.75619print(f"{ratio:.1%}") # 75.6%2021# .format() method22print("Hello, {}!".format(name))23print("{0} costs ${1:.2f}".format("Item", 9.99))5. Control Flow
5.1 If-Elif-Else
Python
1score = 8523if score >= 90:4 grade = "A"5elif score >= 80:6 grade = "B"7elif score >= 70:8 grade = "C"9else:10 grade = "F"1112print(f"Grade: {grade}") # Grade: B1314# Ternary operator (one-line if)15status = "Pass" if score >= 60 else "Fail"5.2 For Loop
Python
1# Iterate over list2fruits = ["apple", "banana", "cherry"]3for fruit in fruits:4 print(fruit)56# Range7for i in range(5): # 0, 1, 2, 3, 48 print(i)910for i in range(1, 6): # 1, 2, 3, 4, 511 print(i)1213for i in range(0, 10, 2): # 0, 2, 4, 6, 814 print(i)1516# Enumerate (index + value)17for idx, fruit in enumerate(fruits):18 print(f"{idx}: {fruit}")1920# Zip (parallel iteration)21names = ["Alice", "Bob"]22ages = [25, 30]23for name, age in zip(names, ages):24 print(f"{name} is {age}")5.3 While Loop
Python
1count = 02while count < 5:3 print(count)4 count += 156# With break and continue7while True:8 user_input = input("Enter 'q' to quit: ")9 if user_input == 'q':10 break11 if user_input == '':12 continue13 print(f"You entered: {user_input}")5.4 List Comprehension
Python
1# Basic2squares = [x**2 for x in range(10)]3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]45# With condition6evens = [x for x in range(20) if x % 2 == 0]7# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]89# Nested10matrix = [[i*j for j in range(3)] for i in range(3)]11# [[0,0,0], [0,1,2], [0,2,4]]1213# Dict comprehension14squares_dict = {x: x**2 for x in range(5)}15# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}6. Collections
6.1 List
Python
1# Create2fruits = ["apple", "banana", "cherry"]3numbers = list(range(1, 6))45# Access6fruits[0] # "apple"7fruits[-1] # "cherry"8fruits[1:3] # ["banana", "cherry"]910# Modify11fruits.append("orange") # Add to end12fruits.insert(1, "grape") # Insert at index13fruits.extend(["kiwi"]) # Add multiple14fruits.remove("banana") # Remove by value15fruits.pop() # Remove last16fruits.pop(0) # Remove by index1718# Other methods19fruits.sort() # Sort in place20fruits.reverse() # Reverse in place21fruits.index("apple") # Find index22fruits.count("apple") # Count occurrences6.2 Dictionary
Python
1# Create2person = {3 "name": "Alice",4 "age": 25,5 "city": "Hanoi"6}78# Access9person["name"] # "Alice"10person.get("name") # "Alice"11person.get("job", "N/A") # "N/A" (default)1213# Modify14person["age"] = 26 # Update15person["job"] = "Data Scientist" # Add new1617# Methods18person.keys() # dict_keys(['name', 'age', 'city', 'job'])19person.values() # dict_values(['Alice', 26, 'Hanoi', 'Data Scientist'])20person.items() # dict_items([('name', 'Alice'), ...])2122# Iterate23for key, value in person.items():24 print(f"{key}: {value}")6.3 Set & Tuple
Python
1# Set - Unique values, unordered2colors = {"red", "green", "blue"}3colors.add("yellow")4colors.remove("red")56# Set operations7a = {1, 2, 3}8b = {2, 3, 4}9print(a | b) # Union: {1, 2, 3, 4}10print(a & b) # Intersection: {2, 3}11print(a - b) # Difference: {1}1213# Tuple - Immutable list14point = (10, 20)15x, y = point # UnpackingTổng Kết
Trong bài này, bạn đã học:
- ✅ Khai báo và đặt tên biến
- ✅ Các kiểu dữ liệu cơ bản
- ✅ Operators và expressions
- ✅ String operations và formatting
- ✅ Control flow: if, for, while
- ✅ Collections: List, Dict, Set, Tuple
Bài tiếp theo: Functions và Error Handling trong Python!
