Python Variables và Data Types

Tìm hiểu về biến, kiểu dữ liệu cơ bản trong Python: strings, numbers, booleans, lists và dictionaries.

Variables trong Python

Variables (biến) là containers để lưu trữ dữ liệu. Python là dynamically typed - không cần khai báo type.

# Khai báo biến - không cần từ khóa
name = "Alice"          # string
age = 25                # integer
height = 1.75           # float
is_hacker = True        # boolean

# Python tự động xác định type
print(type(name))       # <class 'str'>
print(type(age))        # <class 'int'>
print(type(height))     # <class 'float'>
print(type(is_hacker))  # <class 'bool'>

Quy tắc đặt tên

# Hợp lệ
user_name = "admin"
userName = "admin"      # camelCase
_private = "secret"
port443 = True

# KHÔNG hợp lệ
# 2fast = "error"       # Không bắt đầu bằng số
# user-name = "error"   # Không dùng dấu gạch ngang
# class = "error"       # Không dùng reserved words

Convention trong Python (PEP 8)

# Variables và functions: snake_case
user_name = "admin"
max_connections = 100

# Constants: UPPER_SNAKE_CASE
MAX_RETRIES = 3
DEFAULT_PORT = 8080

# Classes: PascalCase
class NetworkScanner:
    pass

Data Types cơ bản

Strings (str)

# Khai báo strings
single = 'Hello'
double = "World"
multi_line = """
Đây là multi-line
string với triple quotes
"""

# String operations
name = "Python"
print(len(name))        # 6 - độ dài
print(name.upper())     # PYTHON
print(name.lower())     # python
print(name[0])          # P - first character
print(name[-1])         # n - last character
print(name[0:3])        # Pyt - slicing

# String formatting
version = 3.12
print(f"Python {version}")              # f-strings (recommended)
print("Python {}".format(version))      # .format()
print("Python %s" % version)            # % formatting (old)

Numbers (int, float)

# Integers
port = 443
connections = 1000
hex_value = 0xFF        # 255
binary = 0b1010         # 10

# Floats
temperature = 36.6
pi = 3.14159

# Operations
print(10 + 3)   # 13 - Addition
print(10 - 3)   # 7  - Subtraction
print(10 * 3)   # 30 - Multiplication
print(10 / 3)   # 3.333... - Division (float)
print(10 // 3)  # 3  - Floor division
print(10 % 3)   # 1  - Modulo
print(10 ** 3)  # 1000 - Power

# Type conversion
float_num = 3.7
int_num = int(float_num)    # 3 (truncate)
str_num = str(int_num)      # "3"

Booleans (bool)

is_active = True
is_admin = False

# Boolean operations
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

# Comparisons return booleans
print(5 > 3)            # True
print(5 == 5)           # True
print(5 != 3)           # True
print(5 >= 5)           # True

# Truthy và Falsy
# Falsy: False, None, 0, 0.0, "", [], {}, set()
# Truthy: mọi thứ khác

if "hello":     # Truthy
    print("Non-empty string is truthy")

if not []:      # [] is Falsy
    print("Empty list is falsy")

Collections

Lists

# List - mutable, ordered collection
ports = [80, 443, 8080, 22]
mixed = [1, "hello", True, 3.14]

# Access elements
print(ports[0])         # 80
print(ports[-1])        # 22
print(ports[1:3])       # [443, 8080]

# Modify
ports.append(3306)      # Add to end
ports.insert(0, 21)     # Insert at position
ports.remove(80)        # Remove by value
ports.pop()             # Remove last
ports[0] = 20           # Update by index

# List methods
print(len(ports))           # Length
print(443 in ports)         # True - check membership
ports.sort()                # Sort in place
sorted_ports = sorted(ports) # Return new sorted list
ports.reverse()             # Reverse in place

# List comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

even = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Dictionaries

# Dictionary - key:value pairs
user = {
    "username": "admin",
    "password": "secret123",
    "port": 22,
    "is_active": True
}

# Access
print(user["username"])         # admin
print(user.get("email", "N/A")) # N/A (default if not found)

# Modify
user["email"] = "admin@pion.dev"  # Add new key
user["port"] = 443                # Update existing
del user["password"]              # Delete key

# Methods
print(user.keys())      # dict_keys(['username', 'port', ...])
print(user.values())    # dict_values(['admin', 443, ...])
print(user.items())     # dict_items([('username', 'admin'), ...])

# Iterate
for key, value in user.items():
    print(f"{key}: {value}")

# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Tuples

# Tuple - immutable, ordered
coordinates = (10, 20, 30)
single_element = (42,)  # Note the comma!

# Access (same as list)
print(coordinates[0])   # 10
print(coordinates[1:])  # (20, 30)

# Cannot modify!
# coordinates[0] = 5    # TypeError!

# Tuple unpacking
x, y, z = coordinates
print(x, y, z)          # 10 20 30

# Common use: multiple return values
def get_server_info():
    return ("192.168.1.1", 443, "HTTPS")

ip, port, protocol = get_server_info()

Sets

# Set - unique, unordered
ports = {80, 443, 8080, 80}  # {80, 443, 8080} - no duplicates
empty_set = set()            # Note: {} creates empty dict!

# Operations
ports.add(22)
ports.remove(80)
ports.discard(9999)     # No error if not found

# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(set_a | set_b)    # Union: {1, 2, 3, 4, 5, 6}
print(set_a & set_b)    # Intersection: {3, 4}
print(set_a - set_b)    # Difference: {1, 2}
print(set_a ^ set_b)    # Symmetric diff: {1, 2, 5, 6}

None Type

# None - represents "nothing"
result = None

def find_user(username):
    users = {"admin": "Admin User", "guest": "Guest User"}
    return users.get(username, None)

user = find_user("hacker")
if user is None:
    print("User not found!")

Type Hints (Python 3.5+)

# Type hints cho code rõ ràng hơn
def scan_port(host: str, port: int) -> bool:
    """Scan a single port on host"""
    # Implementation
    return True

# Complex types
from typing import List, Dict, Optional

def get_open_ports(host: str) -> List[int]:
    return [80, 443, 22]

def get_user(user_id: int) -> Optional[Dict]:
    # Returns dict or None
    return {"id": user_id, "name": "admin"}

Bài tập thực hành

# Bài tập: Target info dictionary
target = {
    "ip": "192.168.1.100",
    "hostname": "webserver01",
    "ports": [22, 80, 443, 3306],
    "os": "Ubuntu 22.04",
    "services": {
        22: "SSH",
        80: "HTTP",
        443: "HTTPS",
        3306: "MySQL"
    }
}

# In thông tin
print(f"Target: {target['hostname']} ({target['ip']})")
print(f"OS: {target['os']}")
print("Open ports:")
for port in target['ports']:
    service = target['services'].get(port, "Unknown")
    print(f"  - {port}: {service}")

Bước tiếp theo

Trong bài tiếp theo, chúng ta sẽ học về:

  • Control Flow: if/else, loops
  • Functions: Định nghĩa và gọi functions
  • Error Handling: try/except

💡 Security tip: Không bao giờ hardcode passwords trong code. Sử dụng environment variables hoặc secrets management.