0% found this document useful (0 votes)
35 views10 pages

Practice 2.ipynb - Colab

The document contains Python code snippets for various programming exercises, including counting vowels, checking for prime numbers, managing student records, and implementing a simple shop and library management system. It demonstrates functions for reading and writing files, handling user input, and performing basic operations like adding, updating, and deleting records. Additionally, it includes functions for character counting, case swapping, finding maximum values in lists, and checking for perfect numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views10 pages

Practice 2.ipynb - Colab

The document contains Python code snippets for various programming exercises, including counting vowels, checking for prime numbers, managing student records, and implementing a simple shop and library management system. It demonstrates functions for reading and writing files, handling user input, and performing basic operations like adding, updating, and deleting records. Additionally, it includes functions for character counting, case swapping, finding maximum values in lists, and checking for perfect numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

7/6/25, 11:14 PM Practice 2.

ipynb - Colab

#Bài 1: Trả về số lượng nguyên âm trong chuỗi, không phân biệt hoa thường
def count_vowels(s: str) -> int:
vowels = "aeiuo"
s = s.lower()
count = 0
for char in s:
if char in vowels:
count += 1
return count

print(count_vowels("Hai Yen"))
print(count_vowels("XYZ"))

3
0

#Bài 2: Kiểm tra xem 1 số nguyên dương có phải là số nguyên tố không


def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n**0.5) + 1): #xét từ 2 đến căn n, có số nào chia hết thì không phải
if n % i == 0:
return False
return True

print(is_prime(5))
print(is_prime(21))

True
False

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 1/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

#Bài 3:
def manage_students():
students = []
while True:
st_code = input("Enter student code: ")
if st_code == "":
break
name = input("Enter student's name: ")
score = float(input("Enter student's score: "))
students.append({
"Student code": st_code,
"Name": name,
"Score": score
})

return students

manage_students()

Enter student code: 1123


Enter student's name: hai yen
Enter student's score: 9.5
Enter student code:
[{'Student code': '1123', 'Name': 'hai yen', 'Score': 9.5}]

#Bài 4: Đọc dữ liệu sp từ file và hiển thị menu quản lý cửa hàng với các mục
def create_sample(filename: str):
sample_data = [
"P001,Laptop,15000000",
"P002,Mouse,300000",
"P003,Keyboard,800000"
]
with open(filename, "w") as f:
for line in sample_data:
f.write(line + "\n")
print(f"File 'filename' created with sample products")

def load_products(filename: str) -> dict:


products = {}
try:
with open(filename, "r", encoding="utf-8") as f:
for line in f:
product_id, name, price = line.strip().split(",")
products[product_id] = {"name": name, "price": int(price)}
except FileNotFoundError:
print(f"File '{filename}' not found. Starting with an empty product list.")
return products

def shop_menu(products: dict) -> None:


while True:
print("\n----- SHOP MANAGEMENT -----")
https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 2/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

print("1. View products")


print("2. Add product")
print("3. Update price")
print("4. Delete product")
print("5. Search product")
print("6. Exit")
choice = input("Choose: ").strip()

if choice == "1":
if not products:
print("No products available.")
else:
for pid, info in products.items():
print(f"ID: {pid}, Name: {info['name']}, Price: {info['price']}")
elif choice == "2":
pid = input("Enter product ID: ").strip()
if pid in products:
print("Product ID already exists.")
else:
name = input("Enter product name: ").strip()
try:
price = int(input("Enter price: ").strip())
products[pid] = {"name": name, "price": price}
print("Product added successfully!")
except ValueError:
print("Invalid price.")
elif choice == "3":
pid = input("Enter product ID to update: ").strip()
if pid not in products:
print("Product ID not found.")
else:
try:
new_price = int(input("Enter new price: ").strip())
products[pid]["price"] = new_price
print("Price updated successfully!")
except ValueError:
print("Invalid price.")
elif choice == "4":
pid = input("Enter product ID to delete: ").strip()
if pid in products:
del products[pid]
print("Product deleted.")
else:
print("Product ID not found.")
elif choice == "5":
keyword = input("Enter product name to search: ").strip().lower()
found = False
for pid, info in products.items():
if keyword in info["name"].lower():
print(f"ID: {pid}, Name: {info['name']}, Price: {info['price']}")
found = True

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 3/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

if not found:
print("No matching products found.")
elif choice == "6":
print("Exiting shop management.")
break
else:
print("Invalid choice. Please choose 1–6.")

filename = "products.txt"
create_sample(filename)
products = load_products(filename)
shop_menu(products)

File 'filename' created with sample products

----- SHOP MANAGEMENT -----


1. View products
2. Add product
3. Update price
4. Delete product
5. Search product
6. Exit
Choose: 1
ID: P001, Name: Laptop, Price: 15000000
ID: P002, Name: Mouse, Price: 300000
ID: P003, Name: Keyboard, Price: 800000

----- SHOP MANAGEMENT -----


1. View products
2. Add product
3. Update price
4. Delete product
5. Search product
6. Exit
Choose: 2
Enter product ID: P004
Enter product name: Phonecase
Enter price: 40000
Product added successfully!

----- SHOP MANAGEMENT -----


1. View products
2. Add product
3. Update price
4. Delete product
5. Search product
6. Exit
Choose: 6
Exiting shop management.

#Bài 5: Quản lý thư viện


def create_sample_files():
with open("books.txt", "w", encoding="utf-8") as f:
f.write("B001,Python Programming,John Doe,available\n")
https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 4/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

f.write("B002,Web Development,Jane Smith,borrowed\n")


f.write("B003,Data Science,Bob Johnson,available\n")

with open("members.txt", "w", encoding="utf-8") as f:


f.write("M001,Nguyen Van A,B002\n")
f.write("M002,Tran Thi B,\n")

print("Sample files created successfully.")

def load_books(filename="books.txt") -> dict:


books = {}
with open(filename, "r", encoding="utf-8") as f:
for line in f:
book_id, title, author, status = line.strip().split(",")
books[book_id] = {"title": title, "author": author, "status": status}
return books

def load_members(filename="members.txt") -> dict:


members = {}
with open(filename, "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split(",")
member_id = parts[0]
name = parts[1]
borrowed = parts[2].split(";") if len(parts) > 2 and parts[2] else []
members[member_id] = {"name": name, "borrowed_books": borrowed}
return members

def save_books(books: dict, filename="books.txt"):


with open(filename, "w", encoding="utf-8") as f:
for book_id, info in books.items():
f.write(f"{book_id},{info['title']},{info['author']},{info['status']}\n")

def save_members(members: dict, filename="members.txt"):


with open(filename, "w", encoding="utf-8") as f:
for member_id, info in members.items():
borrowed = ";".join(info["borrowed_books"])
f.write(f"{member_id},{info['name']},{borrowed}\n")

def library_system():
books = load_books()
members = load_members()

while True:
print("\n----- LIBRARY MANAGEMENT -----")
print("1. View books")
print("2. Borrow book")
print("3. Return book")
print("4. View member info")
print("5. Add new book")
print("6. Exit")

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 5/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

choice = input("Choose: ").strip()

if choice == "1":
for book_id, info in books.items():
print(f"{book_id} - {info['title']} by {info['author']} ({info['status']})")

elif choice == "2":


member_id = input("Enter member ID: ").strip()
if member_id not in members:
print("Member not found.")
continue
book_id = input("Enter book ID to borrow: ").strip()
if book_id not in books:
print("Book not found.")
elif books[book_id]["status"] != "available":
print("Book is already borrowed.")
else:
books[book_id]["status"] = "borrowed"
members[member_id]["borrowed_books"].append(book_id)
print("Book borrowed successfully.")
save_books(books)
save_members(members)

elif choice == "3":


member_id = input("Enter member ID: ").strip()
if member_id not in members:
print("Member not found.")
continue
book_id = input("Enter book ID to return: ").strip()
if book_id in members[member_id]["borrowed_books"]:
members[member_id]["borrowed_books"].remove(book_id)
books[book_id]["status"] = "available"
print("Book returned successfully.")
save_books(books)
save_members(members)
else:
print("This member did not borrow this book.")

elif choice == "4":


member_id = input("Enter member ID: ").strip()
if member_id not in members:
print("Member not found.")
else:
info = members[member_id]
print(f"Name: {info['name']}")
if info["borrowed_books"]:
print("Borrowed books:")
for bid in info["borrowed_books"]:
book = books.get(bid)
if book:
print(f" {bid} - {book['title']}")

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 6/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

else:
print("No borrowed books.")

elif choice == "5":


book_id = input("Enter new book ID: ").strip()
if book_id in books:
print("Book ID already exists.")
else:
title = input("Enter book title: ").strip()
author = input("Enter author: ").strip()
books[book_id] = {"title": title, "author": author, "status": "available"}
print("Book added successfully.")
save_books(books)

elif choice == "6":


print("Exiting library system.")
break

else:
print("Invalid choice. Please choose 1–6.")

create_sample_files()
library_system()

Sample files created successfully.

----- LIBRARY MANAGEMENT -----


1. View books
2. Borrow book
3. Return book
4. View member info
5. Add new book
6. Exit
Choose: 1
B001 - Python Programming by John Doe (available)
B002 - Web Development by Jane Smith (borrowed)
B003 - Data Science by Bob Johnson (available)

----- LIBRARY MANAGEMENT -----


1. View books
2. Borrow book
3. Return book
4. View member info
5. Add new book
6. Exit
Choose: 2
Enter member ID: 432
Member not found.

----- LIBRARY MANAGEMENT -----


1. View books
2. Borrow book
3. Return book
4. View member info
https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 7/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab
5. Add new book
6. Exit
Choose: 4
Enter member ID: B001
Member not found.

----- LIBRARY MANAGEMENT -----


1. View books
2. Borrow book
3. Return book
4. View member info
5. Add new book
6. Exit
Choose: 6
Exiting library system.

# Đếm ký tự
def count_char(s: str, char: str) -> int:
s = s.lower()
s = s.count(char)
return s

print(count_char("hello", "l"))
print(count_char("haiyen", "a"))

2
1

# Chuyển đổi case:


def swap_case(s: str) -> str:
result = ""
for char in s:
if char.islower():
result += char.upper()
else:
result += char.lower()
return result

swap_case("Hello World")

'hELLO wORLD'

# Tìm số lớn nhất trong list


def find_max(numbers: list) -> int:
return max(numbers)

find_max([1, 2, 3, 4])

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 8/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

# Kiểm tra số hoàn hảo:


def is_perfect_number(n: int) -> bool:
if n < 2:
return False

total = 1 # 1 luôn là ước của mọi số


for i in range(2, int(n**0.5) + 1):
if n % i == 0:
total += i
if i != n // i:
total += n // i
return total == n

print(is_perfect_number(6))

True

# Tính giai thừa:


def factorial(n: int) -> int:
if n < 0:
raise ValueError
result = 1
for i in range(2, n+1):
result *= i
return result

print(factorial(8))

40320

# Chuyển đổi số thập phân sang nhị phân


def decimal_to_binary(n: int) -> str:
if n == 0:
return "0"

binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary

decimal_to_binary(10)

'1010'

# Bài toán quản lý sản phẩm:


def create_products():
with open("products.txt", "w") as f:
while True:
product_id = input("Enter product ID: ").strip()
https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 9/10
7/6/25, 11:14 PM Practice 2.ipynb - Colab

if product_id == "":
break

name = input("Enter product name: ").strip()


try:
price = int(input("Enter product price: ").strip())
except ValueError:
print("Invalid price. Must be a number.")
continue

line = f"{product_id},{name},{price}\n"
f.write(line)
print("Product saved.\n")
print("All products saved to 'products.txt")

create_products()

Enter product ID: 1234fe


Enter product name: nails
Enter product price: 23
Product saved.

Enter product ID:


All products saved to 'products.txt

https://colab.research.google.com/drive/1TB3kEBnR_eeWn6HuaAHAg7r-piycEKvI#scrollTo=yH7SUXQ-eOxJ&printMode=true 10/10

You might also like