Công Nghệ Python
Giới Thiệu
Python là một ngôn ngữ interpret, có nghĩa là cần có interpret để chạy code Python thành machine code. Bạn có thể tải interpret Python từ trang chủ python.org. Các công cụ biên tập code Python phổ biến gồm PyCharm và VSCode.
Chuỗi
print("1")
print('qwq')
# Kết nối chuỗi
print("1" + "qwq")
# Chuyển dòng
print("1qwq\nqwqqwqw")
# Chữ cái特价
print("1qwq\"qwqw")
# Chuỗi nhiều dòng
print("""
qwqwqqw
qwqwqwq
""")
Các Kiểu Dữ Liệu
- Integer: int - số nguyên
- Float: float - số thực
- Boolean: bool - hai giá trị True và False (lưu ý chữ hoa)
- String: str - có thể truy cập phần tử qua chỉ mục, bắt đầu từ 0
- NoneType: None - kiểu dữ liệu rỗng trong Python
- Sử dụng hàm type() để lấy kiểu dữ liệu của biến
# Ví dụ về kiểu dữ liệu
str_var = "qwq"
print(str_var[0]) # In ra 'q'
is_true = True
is_false = False
value = None
print(type(str_var)) # In ra <class 'str'>
Biến
Trong Python, không cần khai báo kiểu dữ liệu khi khai báo biến. Các quy tắc đặt tên biến:
- Được phép sử dụng: chữ cái, số, và ký tự gạch chân _
- Không được bắt đầu bằng số
- Biến nhạy cảm với регистр
giá_trị = 1
giá_trị2 = 1.0
giá_trị3 = " chuỗi "
Comment
- Comment một dòng: #
- Comment nhiều dòng: """ """
# Comment một dòng
"""
Comment nhiều dòng
"""
Operateurs Lô Gíc
Các operateur lô gíc trong Python: and (và), or (hoặc), not (không)
Keyword Pass
Khi không có code cần viết trong hàm hay lớp, có thể dùng pass để không gây lỗi
Annotate Kiểu Dữ Liệu
Từ Python 3.5, có thể annotate kiểu dữ liệu. Annotate là tính năng nhắc nhở, không bắt buộc tuân thủ.
var1: int = 100
var2: bool = True
var3: str = "qwq"
var_1: list[int] = [1, 2, 3]
var_2: dict[str, int] = {"value1": 100}
class Student:
pass
var: Student = Student()
Operateurs
+
-
*
/
// # Chia lấy phần nguyên
% # Lấy dư
** # Lấy幂
Chuỗi
Các cách khai báo chuỗi:
- 'Đơn giản'
- "Đôi"
- """ Chuỗi nhiều dòng """
a = "1234"
print("qwq" + a)
a = 1.01
print("qwq" + str(a))
Biến Tùy Chọn
name = "littleD"
message = "Xin chào %s %s" % (name, name)
message = f"Xin chào {name}" # Format string
Xử Lýchuỗi
strings = "lited"
a = strings[0] # 'l'
index = strings.index("ite") # Trả về vị trí bắt đầu
new_string = strings.replace("d", "D") # Thay thế và trả về chuỗi mới
result = "1-1-2-qwq".split("-") # ['1', '1', '2', 'qwq']
Biến Lô Gíc
Giá trị True là đúng, False là sai. Python nhạy cảm với регистр.
Câu Lệnh Điều Khiển
if condition:
# Code khi đúng
elif another_condition:
# Code khi điều kiện này đúng
else:
# Code khi không đúng các trên
Vòng Lặp
LặpForKeyword For
for i in range(5):
print(i) # 0,1,2,3,4
for i in range(3, 5):
print(i) # 3,4
for i in range(3, 10, 2):
print(i) # 3,5,7,9
Lặp qua Container
names = ["1", "2", 3, 4]
for name in names:
print(f"Cái tên này là {name}")
names_dict = {"1": 123, "2": 123, "3": 123}
for key, value in names_dict.items():
print(f"Key: {key}, Value: {value}")
Vòng Lặp While
i = 0
while i <= 5:
print(i)
i += 1
Hàm
Khai Báo Hàm
def function_name(param1, param2):
# Code
return value # Mặc định trả về None
Biến Trong Hàm
- Biến cục bộ: Chỉ có hiệu lực trong hàm
- Biến toàn cục: Hiệu lực khắp module
a = 100
def test():
global a
a = 10
test()
print(a) # 10
Tham Số Tùy Chọn
def method(t1, t2, t3="Mặc định"):
pass
method(1, 2)
Tham Số Linh Tinh
def test(*args):
for arg in args:
print(arg)
test(1, 2, 3, 4)
def test(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
test(name="qwq", age=1)
Trả Về Nhiều Giá Trị
def method():
a, b = 1, 2
return a, b
x, y = method()
Lambda
fun = lambda a: a + 1
print(fun(3)) # 4
method(lambda x, y: x + y)
Quản Lý Tài Liệu
Mở File
open(tên_file, mode, encoding)
Đọc File
with open("file.txt", "r", encoding="utf-8") as f:
print(f.read())
Ghi File
with open("file.txt", "w", encoding="utf-8") as file:
file.write("Content")
Xử Lý Ngoại Lệ
try:
# Code có thể gây ngoại lệ
except ValueError:
print("Xảy ra ValueError")
except NameError as e:
print(e)
except (ValueError, NameError) as e:
print(e)
else:
# Code khi không có ngoại lệ
finally:
# Code luôn thực thi
Module
Khai Báo Module
import module_name
from module_name import function_name
from module_name import *
import module_name as alias
Tự_Define Module
def my_function():
print("Hello")
if __name__ == '__main__':
my_function()
Package
- Folder chứa các module
- Sử dụng file init.py để kiểm soát package
Tùy Chọn Third-Party
Sử dụng pip để cài đặt:
pip install package_name
pip install --mirror mirror_url package_name
Lập Trình Đối Tượng
Khai Báo Class
class MyClass:
def __init__(self, param):
self.param = param
def my_method(self, arg):
pass
obj = MyClass("value")
obj.my_method(1)
Phương Thơm Magic
class Student:
def __str__(self):
return f"Object Student"
def __lt__(self, other):
return self.age < other.age
Biến Riêng
class MyClass:
__private_var = None
def __private_method(self):
print("Method riêng")
def public_method(self):
self.__private_method()
Di承IODevice
class Conductor(Device):
def __init__(self, param1, param2, param3):
super().__init__(param1, param2)
self.param3 = param3
Closures và Decorators
Closures
def outer(a):
b = 1
def inner():
nonlocal a, b
return a + b
return inner
Decorators
def outer(func):
def inner():
print("Trước khi gọi hàm")
func()
print("Sau khi gọi hàm")
return inner
@outer
def my_func():
print("Hàm được gọi")
my_func()
Multi-Threading
Sử Dụng Thread
import threading
def worker(message):
print(message)
thread = threading.Thread(target=worker, args=("Xin chào",))
thread.start()
Pool Thread
from concurrent.futures import ThreadPoolExecutor
import time
def process(x):
print(x)
time.sleep(2)
with ThreadPoolExecutor(max_workers=4) as executor:
executor.submit(process, "1")
executor.submit(process, "2")
###Coroutine
import asyncio
async def coroutine():
print("Tôi là một coroutine")
await asyncio.sleep(1)
print("Tôi đã hoàn thành")
async def main():
await coroutine()
asyncio.run(main())
Biểu.Regular Expression
import re
pattern = r"^\d{3}-\d{3}-\d{4}$"
text = "098-765-4321"
match = re.fullmatch(pattern, text)
if match:
print("Valid phone number")
else:
print("Invalid phone number")
Quản Lý Vironment.with venv
python -m venv myenv
source myenv/bin/activate # Unix/Mac
myenv\Scripts\activate.bat # Windows
deactivate # Thoát vironment
Tóm Lại
Bài viết này đã giới thiệu các khái niệm cơ bản và các tính năng chính của ngôn ngữ Python, bao gồm các loại dữ liệu, biến, comment, operateurs, hàm, xử lý file, ngoại lệ, module, và hơn nữa.