Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
>>> import math
>>> x = 99
>>> math.sqrt(x)
| Loại | Mô tả | Ví dụ |
|---|---|---|
| Thư viện chuẩn | Có sẵn trong mọi bản cài Python, dùng ngay | math, random, datetime |
| Thư viện ngoài | Cài thêm bằng trình quản lý gói (ví dụ pip) | pandas, matplotlib, numpy |
Gợi ý: ưu tiên thư viện chuẩn khi đủ dùng; dùng thư viện ngoài khi cần năng lực chuyên sâu.
| Hằng số | Ý nghĩa | Ghi chú |
|---|---|---|
| math.pi | π ≈ 3.1415 | Dùng cho đường tròn, mặt cầu |
| math.e | e ≈ 2.71828 | Nền tảng log tự nhiên, giải tích |
Ví dụ: tính chu vi đường tròn
import math
radius = 5
circumference = 2*math.pi*radius
print(circumference)
| Hàm | Mô tả | Ví dụ |
|---|---|---|
| math.ceil(x) | Làm tròn lên | print(math.ceil(4.1)) → 5 |
| math.floor(x) | Làm tròn xuống | print(math.floor(4.9)) → 4 |
| math.trunc(x) | Cắt phần thập phân |
math.trunc(4.9) → 4 math.trunc(-4.1) → -4 |
import math
print(math.ceil(4.1)) # Output: 5
print(math.floor(4.9)) # Output: 4
print(math.trunc(4.9)) # Output: 4
print(math.trunc(-4.1)) # Output: -4
import math
print(math.pow(2, 3)) # Output: 8.0
print(2**3) # Output: 8
print(math.sqrt(25)) # Output: 5.0
Ứng dụng: định lý Pythagoras
import math
a = 3
b = 4
hypotenuse = math.sqrt(math.pow(a, 2) + math.pow(b, 2))
print(f"Hypotenuse: {hypotenuse}") # Output: 5.0
import random
print(random.random()) # ví dụ: 0.95...
print(random.randint(1, 10)) # trả về số nguyên từ 1 đến 10
import random
choices = ["Rock", "Paper", "Scissors"]
choice = random.choice(choices)
print(choice)
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
import datetime
current_time = datetime.datetime.now()
print(current_time)
Thường hiển thị theo dạng:
YYYY-MM-DD HH:MM:SS.microseconds
import datetime
christmas = datetime.date(2023, 12, 25)
noon = datetime.time(12, 0, 0)
event = datetime.datetime(2024, 7, 4, 9, 30, 0)
from datetime import datetime, timedelta
today = datetime.now()
seven_days_later = today + timedelta(days=7)
print(f"Today: {today.date()}")
print(f"Deadline in 7 days: {seven_days_later.date()}")
Đơn vị thường dùng: days, seconds, minutes, hours, weeks.
| Mã | Ý nghĩa | Ví dụ |
|---|---|---|
| %Y | Năm đầy đủ | 2023 |
| %m | Tháng (01–12) | 01 |
| %d | Ngày (01–31) | 25 |
| %H | Giờ (00–23) | 14 |
| %M | Phút (00–59) | 05 |
| %S | Giây (00–59) | 09 |
| %A | Tên thứ trong tuần | Monday |
from datetime import datetime
today = datetime.now()
formatted_date = today.strftime("%m/%d/%Y")
print(formatted_date)
Cài thư viện: pip install <tên_thư_viện>.
pip install pandas
pip install matplotlib
| Lệnh | Tác dụng | Gợi ý |
|---|---|---|
| pip list | Liệt kê gói đã cài & phiên bản | ✅ Kiểm tra môi trường |
| pip uninstall | Gỡ cài đặt thư viện | ✅ Dọn dẹp |
| pip install --upgrade | Nâng cấp lên phiên bản mới nhất | ⚠️ Cẩn thận tương thích |
import matplotlib.pyplot as plt
Mục tiêu: làm rõ thông điệp, không chỉ “vẽ cho đẹp”.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("Angle (radians)")
plt.ylabel("Amplitude")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label="sin")
plt.plot(x, y2, label="cos")
plt.legend()
plt.show()
import matplotlib.pyplot as plt
categories = ["Product A", "Product B", "Product C", "Product D", "Product E"]
values = [25, 40, 15, 30, 20]
plt.bar(categories, values, color="skyblue", edgecolor="navy")
plt.xlabel("Categories")
plt.ylabel("Sales (Units)")
plt.title("Monthly Product Performance")
plt.show()
import matplotlib.pyplot as plt
labels = ["Rent", "Groceries", "Utilities", "Entertainment", "Savings"]
sizes = [1200, 450, 200, 150, 500]
colors = ["#ff9999", "#66b3ff", "#99ff99", "#ffcc99", "#c2c2f0"]
plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=140, colors=colors)
plt.axis("equal")
plt.title("Monthly Expense Breakdown")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000)
plt.hist(data, bins=30, color="forestgreen", edgecolor="black", alpha=0.7)
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Data Distribution")
plt.show()
import pandas as pd
s = pd.Series(["welcome", "to", "COM1050"])
print(s.index)
print(s.values)
import pandas as pd
s = pd.Series([4, -2, 0, 6], index=["a", "b", "c", "d"])
print(s["a"])
print(s[["a", "c"]])
mask = s > 0
print(mask)
print(s[mask])
import pandas as pd
elections = pd.read_csv("elections.csv")
print(elections.head())
import pandas as pd
df1 = pd.DataFrame({
"Fruit": ["Strawberry", "Orange"],
"Price": [5.49, 3.99]
})
import pandas as pd
df2 = pd.DataFrame([
{"Fruit": "Strawberry", "Price": 5.49},
{"Fruit": "Orange", "Price": 3.99}
])
import pandas as pd
s_a = pd.Series(["a1", "a2", "a3"], index=["r1", "r2", "r3"])
s_b = pd.Series(["b1", "b2", "b3"], index=["r1", "r2", "r3"])
df = pd.DataFrame({"A-column": s_a, "B-column": s_b})
df_single = pd.DataFrame(s_a)
df_frame = s_a.to_frame()
# khung cú pháp
df.loc[row_labels, column_labels]
# ví dụ minh họa (giả sử có DataFrame elections)
elections.loc[[87, 25, 179], ["Year", "Candidate", "Result"]]
elections.loc[[87, 25, 179], "Popular vote":"%"]
elections.loc[0, "Candidate"]
# khung cú pháp
df.iloc[row_integers, column_integers]
# ví dụ minh họa (giả sử có DataFrame elections)
elections.iloc[[1, 2, 3], [0, 1, 2]]
elections.iloc[[1, 2, 3], 0:3]
elections.iloc[0, 1]
# lấy các hàng 3,4,5,6 (biên phải loại trừ)
elections[3:7]
# chọn nhiều cột
elections[["Year", "Candidate", "Result"]]
⚠️ Lỗi hay gặp: quên ngoặc vuông bên trong.
import numpy as np
yash_count = babynames[babynames["Name"] == "Yash"]["Count"]
print(np.mean(yash_count))
print(np.max(yash_count))
# ví dụ minh họa
df.sort_values(by="Price", ascending=True)
# khung cú pháp
dt.apply(f, axis=1)
import pandas as pd
def calculate_total(row):
"""Calculates price * quantity and adds a shipping fee."""
total = (row["Price"] * row["Quantity"]) + 10
return total
data = {
"Product": ["Laptop", "Mouse", "Monitor", "Keyboard"],
"Price": [1200, 25, 300, 75],
"Quantity": [2, 10, 3, 5]
}
df = pd.DataFrame(data)
df["Total_with_Shipping"] = df.apply(calculate_total, axis=1)
import pandas as pd
import matplotlib.pyplot as plt
data = {"Month": ["Jan", "Feb", "Mar", "Apr", "May"],
"Sales": [2500, 3200, 2100, 4000, 4500]}
df = pd.DataFrame(data)
df.plot(x="Month", y="Sales", kind="line", marker="o", title="Monthly Sales Trend")
plt.show()