0% found this document useful (0 votes)
13 views4 pages

Luyện Python.ipynb - Colab

The document contains a series of Python exercises including calculating factorials, formatting phone numbers, counting word frequency, reading and analyzing sales data, reversing strings, summing digits, creating and loading accounts, and implementing an ATM menu system. Each exercise is accompanied by code snippets demonstrating the functionality. The document serves as a practical guide for learning Python programming concepts.
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)
13 views4 pages

Luyện Python.ipynb - Colab

The document contains a series of Python exercises including calculating factorials, formatting phone numbers, counting word frequency, reading and analyzing sales data, reversing strings, summing digits, creating and loading accounts, and implementing an ATM menu system. Each exercise is accompanied by code snippets demonstrating the functionality. The document serves as a practical guide for learning Python programming concepts.
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/ 4

7/6/25, 11:17 PM luyện python.

ipynb - Colab

#Exercise 1: tính giai thừa


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

factorial(10)
factorial(4)

24

#Exercise 2:
def format_phone(s: str) -> str:
s = [Link](" ", "")
if [Link]("0"):
s = s[1:]

bat_dau = s[:3]
number = s[3:]

return f"(+84) {bat_dau} {number}"

format_phone("0799 214 766")

'(+84) 799 214766'

#Exercise 3: Đếm số từ
def word_frequency(text: str) -> dict:
text = [Link]()
words = [Link]()

freq = {}
for word in words:
freq[word] = [Link](word, 0) + 1
return freq

word_frequency("Hi My name is Yen, Yen is fabulous")

{'hi': 1, 'my': 1, 'name': 1, 'is': 2, 'yen,': 1, 'yen': 1, 'fabulous': 1}

#Exercise 4:
def read_sales() -> list[dict]:
sales = []
while True:
code = input("Enter product code (empty it to stop): ")
if code == "":
break
name = input("Enter product name: ")
price = float(input("Enter product price: "))
quantity = int(input("Enter product quantity: "))

[Link]({
"code": code,
"name": name,
"price": price,
"quantity": quantity
})
return sales

def analyze_sales(data: list[dict]) -> None:


if not data:
return "No sales data to analyze"

total_revenue = 0
max_quantity = 0
max_revenue = 0

for item in data:


revenue = item["price"] * item["quantity"]
item["revenue"] = revenue
total_revenue += revenue
max_quantity = max(max_quantity, item["quantity"])
max_revenue = max(max_revenue, revenue)

[Link] 1/4
7/6/25, 11:17 PM luyện [Link] - Colab

print(f"\nTotal revenue: {total_revenue:.2f}")

print("\nBest-selling product by quantity:")


for item in data:
if item["quantity"] == max_quantity:
print(f"- {item['name']} (Quantity sold: {item['quantity']})")

print(f"\nProduct with highest total revenue:")


for item in data:
if item["revenue"] == max_revenue:
print(f"- {item['name']} (Revenue: {item['revenue']:.2f})")

sales_data = read_sales()
analyze_sales(sales_data)

Enter product code (empty it to stop): 222890478687


Enter product name: spu
Enter product price: 20000000
Enter product quantity: 5
Enter product code (empty it to stop):

Total revenue: 100000000.00

Best-selling product by quantity:


- spu (Quantity sold: 5)

Product with highest total revenue:


- spu (Revenue: 100000000.00)

#Viết chữ đảo ngược


def reverse_string(s: str) -> str:
return s[::-1]

print(reverse_string("Hello"))
print(reverse_string("HaiYen"))

olleH
neYiaH

#Tính tổng các chữ số


def sum_of_digits(n: int) -> int:
total = 0
for digit in str(n):
total += int(digit)
return total

print(sum_of_digits(1234))
print(sum_of_digits(2110))

10
4

#Exercise 3:
def create_accounts():
with open('[Link]', "w") as f:
accounts = []
while True:
account_number = input("Enter account number: ")
if account_number == "":
break
owner = input("Enter owner: ")
balance = float(input("Enter balance: "))

[Link]({
"account number": account_number,
"owner": owner,
"balance": balance
})
return accounts
[Link](f"{account_number}, {owner}, {balance}\n")

create_accounts()

Enter account number: 333


Enter owner: nguyen le huy
Enter balance: 10.00

[Link] 2/4
7/6/25, 11:17 PM luyện [Link] - Colab
Enter account number: 111
Enter owner: giang ngoc
Enter balance: 20.00
Enter account number:
[{'account number': '333', 'owner': 'nguyen le huy', 'balance': 10.0},
{'account number': '111', 'owner': 'giang ngoc', 'balance': 20.0}]

#Exercise 4:
def load_account(filename: str) -> dict:
accounts = {}
with open('[Link]', 'r') as f:
for line in f:
account_number, owner, balance = [Link]().split(',')
accounts[account_number.strip()] = {
"owner": [Link](),
"balance": float([Link]())
}
return accounts

def atm_menu(accounts: dict) -> None:


login = input("Enter account number: ").strip()

if login not in accounts:


print("Account is not found")
return

current = accounts[login]
print(f"Welcome, {current['owner']}")

while True:
print("\n----- ATM MENU -----")
print("1. View balance")
print("2. Deposit money")
print("3. Withdraw money")
print("4. Transfer money")
print("5. Exit")

choice = input("Select an option (1-5): ").strip()

if choice == "1":
print(f"Balance: {current['balance']} VND")
elif choice == "2":
amount = float(input("Enter deposit amount: "))
if amount > 0:
current['balance'] += amount
print(f"Deposited {amount} VND")
else:
print("Invalid amount")

elif choice == "3":


amount = float(input("Enter withdrawal amount: "))
if 0 < amount <= current['balance']:
current['balance'] -= amount
print(f"Withdrew {amount} VND")
else:
print("Insufficient funds or invalid amount")

elif choice == "4":


target_acc = input("Enter destination account number: ").strip()
if target_acc not in accounts:
print("Destination account not found")
continue
amount = float(input("Enter amount to transfer: "))
if 0 < amount <= current['balance']:
current['balance'] -= amount
print(f"Transferred {amount} VND to {accounts[target_acc]['owner']}")
else:
print("Insufficient funds or invalid amount")

elif choice == "5":


print("Exit")
break

else:
print("Invalid choice")

def main():

[Link] 3/4
7/6/25, 11:17 PM luyện [Link] - Colab
accounts = load_account('[Link]')
atm_menu(accounts)

if __name__ == "__main__":
main()

Hiện kết quả đã ẩn

[Link] 4/4

You might also like