Lý thuyết
Bài 3/14

Cú Pháp Python Cơ Bản

Variables, Data Types, Operators và Control Flow trong Python

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ản
2name = "MinAI" # String
3age = 25 # Integer
4price = 19.99 # Float
5is_active = True # Boolean
6
7# Multiple assignment
8x, y, z = 1, 2, 3
9a = b = c = 0
10
11# Swap values (Pythonic way!)
12x, y = y, x

1.2 Quy tắc đặt tên biến

Python
1# ✅ Hợp lệ
2my_variable = 1
3myVariable = 2 # camelCase
4MyVariable = 3 # PascalCase
5my_variable_2 = 4
6_private = 5
7
8# ❌ Không hợp lệ
92variable = 1 # Bắt đầu bằng số
10my-variable = 2 # Có dấu gạch ngang
11my variable = 3 # Có khoảng trắng

1.3 Convention trong Python (PEP 8)

LoạiConventionVí dụ
Variablesnake_caseuser_name
ConstantUPPER_SNAKEMAX_SIZE
Functionsnake_casecalculate_total()
ClassPascalCaseDataProcessor
Private_prefix_internal_var

2. Data Types (Kiểu dữ liệu)

2.1 Primitive Types

Python
1# Integer - Số nguyên
2count = 42
3big_num = 1_000_000 # Underscore cho dễ đọc
4
5# Float - Số thực
6pi = 3.14159
7scientific = 1.5e-10 # 1.5 × 10^-10
8
9# String - Chuỗi
10name = "Python"
11message = 'Hello World'
12multiline = """
13This is a
14multiline string
15"""
16
17# Boolean
18is_valid = True
19is_empty = False
20
21# None - Giá trị null
22result = None

2.2 Kiểm tra kiểu dữ liệu

Python
1x = 42
2print(type(x)) # <class 'int'>
3print(isinstance(x, int)) # True
4
5# Kiểm tra nhiều kiểu
6print(isinstance(x, (int, float))) # True

2.3 Type Conversion

Python
1# String to Number
2num_str = "42"
3num_int = int(num_str) # 42
4num_float = float(num_str) # 42.0
5
6# Number to String
7x = 100
8s = str(x) # "100"
9
10# Boolean conversion
11bool(0) # False
12bool(1) # True
13bool("") # False
14bool("text") # True
15bool([]) # False
16bool([1,2]) # True

3. Operators (Toán tử)

3.1 Arithmetic Operators

Python
1a, b = 10, 3
2
3print(a + b) # 13 - Cộng
4print(a - b) # 7 - Trừ
5print(a * b) # 30 - Nhân
6print(a / b) # 3.333... - Chia (float)
7print(a // b) # 3 - Chia lấy phần nguyên
8print(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, 10
2
3print(x == y) # False - Bằng
4print(x != y) # True - Khác
5print(x < y) # True - Nhỏ hơn
6print(x <= y) # True - Nhỏ hơn hoặc bằng
7print(x > y) # False - Lớn hơn
8print(x >= y) # False - Lớn hơn hoặc bằng
9
10# Chained comparison (Pythonic!)
11age = 25
12print(18 <= age < 65) # True

3.3 Logical Operators

Python
1a, b = True, False
2
3print(a and b) # False
4print(a or b) # True
5print(not a) # False
6
7# Short-circuit evaluation
8x = 5
9result = x > 0 and x < 10 # True
10
11# Practical example
12name = ""
13display = name or "Anonymous" # "Anonymous"

3.4 Assignment Operators

Python
1x = 10
2x += 5 # x = x + 5 → 15
3x -= 3 # x = x - 3 → 12
4x *= 2 # x = x * 2 → 24
5x /= 4 # x = x / 4 → 6.0
6x //= 2 # x = x // 2 → 3.0
7x **= 2 # x = x ** 2 → 9.0

4. Strings (Chuỗi)

4.1 String Operations

Python
1s = "Python Data Science"
2
3# Indexing (0-based)
4print(s[0]) # 'P'
5print(s[-1]) # 'e' (từ cuối)
6
7# Slicing [start:end:step]
8print(s[0:6]) # 'Python'
9print(s[7:]) # 'Data Science'
10print(s[::-1]) # Đảo ngược chuỗi
11
12# Length
13print(len(s)) # 19

4.2 String Methods

Python
1text = " Hello World "
2
3# Case methods
4text.lower() # " hello world "
5text.upper() # " HELLO WORLD "
6text.title() # " Hello World "
7text.capitalize() # " hello world "
8
9# Whitespace
10text.strip() # "Hello World"
11text.lstrip() # "Hello World "
12text.rstrip() # " Hello World"
13
14# Find & Replace
15text.find("World") # 8 (index)
16text.replace("World", "Python") # " Hello Python "
17
18# Split & Join
19"a,b,c".split(",") # ['a', 'b', 'c']
20"-".join(['a','b','c']) # "a-b-c"
21
22# Check methods
23"123".isdigit() # True
24"abc".isalpha() # True
25"abc123".isalnum() # True

4.3 String Formatting

Python
1name = "MinAI"
2price = 19.99
3quantity = 3
4
5# f-string (Python 3.6+) - Khuyến nghị!
6print(f"Hello, {name}!")
7print(f"Total: ${price * quantity:.2f}")
8
9# Format specifiers
10num = 1234.5678
11print(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)
16
17# Percentage
18ratio = 0.756
19print(f"{ratio:.1%}") # 75.6%
20
21# .format() method
22print("Hello, {}!".format(name))
23print("{0} costs ${1:.2f}".format("Item", 9.99))

5. Control Flow

5.1 If-Elif-Else

Python
1score = 85
2
3if score >= 90:
4 grade = "A"
5elif score >= 80:
6 grade = "B"
7elif score >= 70:
8 grade = "C"
9else:
10 grade = "F"
11
12print(f"Grade: {grade}") # Grade: B
13
14# Ternary operator (one-line if)
15status = "Pass" if score >= 60 else "Fail"

5.2 For Loop

Python
1# Iterate over list
2fruits = ["apple", "banana", "cherry"]
3for fruit in fruits:
4 print(fruit)
5
6# Range
7for i in range(5): # 0, 1, 2, 3, 4
8 print(i)
9
10for i in range(1, 6): # 1, 2, 3, 4, 5
11 print(i)
12
13for i in range(0, 10, 2): # 0, 2, 4, 6, 8
14 print(i)
15
16# Enumerate (index + value)
17for idx, fruit in enumerate(fruits):
18 print(f"{idx}: {fruit}")
19
20# 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 = 0
2while count < 5:
3 print(count)
4 count += 1
5
6# With break and continue
7while True:
8 user_input = input("Enter 'q' to quit: ")
9 if user_input == 'q':
10 break
11 if user_input == '':
12 continue
13 print(f"You entered: {user_input}")

5.4 List Comprehension

Python
1# Basic
2squares = [x**2 for x in range(10)]
3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4
5# With condition
6evens = [x for x in range(20) if x % 2 == 0]
7# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
8
9# Nested
10matrix = [[i*j for j in range(3)] for i in range(3)]
11# [[0,0,0], [0,1,2], [0,2,4]]
12
13# Dict comprehension
14squares_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# Create
2fruits = ["apple", "banana", "cherry"]
3numbers = list(range(1, 6))
4
5# Access
6fruits[0] # "apple"
7fruits[-1] # "cherry"
8fruits[1:3] # ["banana", "cherry"]
9
10# Modify
11fruits.append("orange") # Add to end
12fruits.insert(1, "grape") # Insert at index
13fruits.extend(["kiwi"]) # Add multiple
14fruits.remove("banana") # Remove by value
15fruits.pop() # Remove last
16fruits.pop(0) # Remove by index
17
18# Other methods
19fruits.sort() # Sort in place
20fruits.reverse() # Reverse in place
21fruits.index("apple") # Find index
22fruits.count("apple") # Count occurrences

6.2 Dictionary

Python
1# Create
2person = {
3 "name": "Alice",
4 "age": 25,
5 "city": "Hanoi"
6}
7
8# Access
9person["name"] # "Alice"
10person.get("name") # "Alice"
11person.get("job", "N/A") # "N/A" (default)
12
13# Modify
14person["age"] = 26 # Update
15person["job"] = "Data Scientist" # Add new
16
17# Methods
18person.keys() # dict_keys(['name', 'age', 'city', 'job'])
19person.values() # dict_values(['Alice', 26, 'Hanoi', 'Data Scientist'])
20person.items() # dict_items([('name', 'Alice'), ...])
21
22# Iterate
23for key, value in person.items():
24 print(f"{key}: {value}")

6.3 Set & Tuple

Python
1# Set - Unique values, unordered
2colors = {"red", "green", "blue"}
3colors.add("yellow")
4colors.remove("red")
5
6# Set operations
7a = {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}
12
13# Tuple - Immutable list
14point = (10, 20)
15x, y = point # Unpacking

Tổ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!