Python: Loops & Conditionals - 40 Practice Exercises
Python: Vòng Lặp & Điều Kiện - 40 Bài Tập Thực Hành
Mục tiêu: Rèn luyện kỹ năng sử dụng vòng lặp (for, while) và câu lệnh điều kiện (if/elif/else) thông qua 40 bài tập được chia thành 4 cấp độ.
Tier 1: Foundations (Nền Tảng) - Exercises 1-10
Cấp độ: Cơ bản - Vòng lặp đơn giản, điều kiện đơn giản
Bài Tập 1: In Số từ 1 đến n (Print Numbers 1 to n)
Đề bài: Nhập một số n. In ra tất cả các số từ 1 đến n, mỗi số trên một dòng.
Problem: Enter a number n. Print all numbers from 1 to n, one per line.
Example Input/Output
Input:
Enter n: 5Output:
1
2
3
4
5Hints (Gợi Ý)
- Dùng vòng lặp for với range(1, n+1)
- In mỗi số trong vòng lặp
- range(1, n+1) tạo số từ 1 đến n
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(1, n + 1): print(i)
Explanation (Giải Thích)
Vietnamese: Vòng lặp for chạy từ 1 đến n. Mỗi lần lặp in ra số i.
English: For loop runs from 1 to n. Each iteration prints number i.
Bài Tập 2: In Số Chẵn từ 2 đến n (Print Even Numbers 2 to n)
Đề bài: Nhập một số n. In ra tất cả các số chẵn từ 2 đến n.
Problem: Enter a number n. Print all even numbers from 2 to n.
Example Input/Output
Input:
Enter n: 10Output:
2
4
6
8
10Hints (Gợi Ý)
- Dùng range(2, n+1, 2) để tạo số chẵn
- Hoặc dùng range(1, n+1) và kiểm tra i % 2 == 0
- Số chẵn cách nhau 2 đơn vị
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(2, n + 1, 2): print(i)
Explanation (Giải Thích)
Vietnamese: range(2, n+1, 2) tạo dãy số bắt đầu từ 2, tăng 2 mỗi lần (chỉ số chẵn).
English: range(2, n+1, 2) creates sequence starting at 2, incrementing by 2 (even numbers only).
Bài Tập 3: In n Dấu Sao (Print n Stars)
Đề bài: Nhập một số n. In ra n dấu sao (*) trên cùng một dòng.
Problem: Enter a number n. Print n asterisks (*) on the same line.
Example Input/Output
Input:
Enter n: 7Output:
* * * * * * *Hints (Gợi Ý)
- Dùng vòng lặp for
- In với end=' ' để ở cùng dòng
- Hoặc dùng print('* ' * n)
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(n): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp in dấu sao với end=' ' để không xuống dòng. print() cuối để xuống dòng mới.
English: Loop prints stars with end=' ' to stay on same line. Final print() for newline.
Bài Tập 4: Nhập và In n Số (Input and Print n Numbers)
Đề bài: Nhập số lượng n, sau đó nhập n số nguyên. In lại mỗi số ngay sau khi nhập.
Problem: Enter count n, then enter n integers. Print each number immediately after input.
Example Input/Output
Input:
Enter count: 3
Enter number: 10
10
Enter number: 25
25
Enter number: 7
7Output:
10
25
7Hints (Gợi Ý)
- Vòng lặp chạy n lần
- Mỗi lần nhập một số
- In số đó ngay lập tức
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) print(number)
Explanation (Giải Thích)
Vietnamese: Vòng lặp n lần. Mỗi lần nhập số và in ngay. Đây là pattern cơ bản của vòng lặp.
English: Loop n times. Each time input number and print immediately. This is a basic loop pattern.
Bài Tập 5: Tổng của n Số (Sum of n Numbers)
Đề bài: Nhập số lượng n, sau đó nhập n số nguyên. Tính và in tổng của n số đó.
Problem: Enter count n, then n integers. Calculate and print the sum.
Example Input/Output
Input:
Enter count: 4
Enter number: 10
Enter number: 20
Enter number: 5
Enter number: 15Output:
Sum: 50Hints (Gợi Ý)
- Khởi tạo biến tổng = 0
- Vòng lặp n lần
- Cộng mỗi số vào tổng
- In tổng sau vòng lặp
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) total = 0 for i in range(n): number = int(input("Enter number: ")) total += number print(f"Sum: {total}")
Explanation (Giải Thích)
Vietnamese: Khởi tạo total = 0. Mỗi lần nhập số, cộng vào total. Cuối cùng in total.
English: Initialize total = 0. Each input, add to total. Finally print total.
Bài Tập 6: Bảng Cửu Chương (Multiplication Table)
Đề bài: Nhập một số n. In bảng cửu chương của n từ 1 đến 10.
Problem: Enter number n. Print multiplication table for n from 1 to 10.
Example Input/Output
Input:
Enter n: 5Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50Hints (Gợi Ý)
- Vòng lặp từ 1 đến 10
- Mỗi lần tính n x i
- In kết quả theo format đẹp
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(1, 11): print(f"{n} x {i} = {n * i}")
Explanation (Giải Thích)
Vietnamese: Vòng lặp từ 1 đến 10. Mỗi lần in phép nhân n x i = kết quả.
English: Loop from 1 to 10. Each time print multiplication n x i = result.
Bài Tập 7: Đếm Số Lượng (Count Numbers)
Đề bài: Nhập số lượng n, sau đó nhập n số bất kỳ. In ra 'Đã nhập n số'.
Problem: Enter count n, then enter n numbers. Print 'Entered n numbers'.
Example Input/Output
Input:
Enter count: 5
(enter 5 numbers)Output:
Entered 5 numbersHints (Gợi Ý)
- Chỉ cần nhập n số
- Không cần xử lý gì
- In thông báo cuối cùng
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) print(f"Entered {n} numbers")
Explanation (Giải Thích)
Vietnamese: Vòng lặp nhập n số nhưng không làm gì. Chỉ in thông báo cuối.
English: Loop inputs n numbers but does nothing with them. Just print message at end.
Bài Tập 8: Tam Giác Sao Tăng Dần (Increasing Star Triangle)
Đề bài: Nhập số n. In tam giác sao: dòng 1 có 1 sao, dòng 2 có 2 sao, ..., dòng n có n sao.
Problem: Enter n. Print star triangle: row 1 has 1 star, row 2 has 2 stars, ..., row n has n stars.
Example Input/Output
Input:
Enter n: 4Output:
*
* *
* * *
* * * *Hints (Gợi Ý)
- Vòng lặp ngoài: dòng từ 1 đến n
- Vòng lặp trong: in i sao
- Dòng i có i sao
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(1, n + 1): for j in range(i): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp ngoài chạy n dòng. Vòng trong in số sao tương ứng với số dòng.
English: Outer loop runs n rows. Inner loop prints stars corresponding to row number.
Bài Tập 9: In Ngược từ n về 1 (Print n to 1 Reverse)
Đề bài: Nhập số n. In các số từ n về 1, mỗi số trên một dòng.
Problem: Enter n. Print numbers from n to 1, one per line.
Example Input/Output
Input:
Enter n: 5Output:
5
4
3
2
1Hints (Gợi Ý)
- Dùng range(n, 0, -1)
- Đếm ngược từ n về 1
- Bước nhảy là -1
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(n, 0, -1): print(i)
Explanation (Giải Thích)
Vietnamese: range(n, 0, -1) tạo dãy đếm ngược từ n về 1.
English: range(n, 0, -1) creates countdown sequence from n to 1.
Bài Tập 10: Lặp Lại Ký Tự (Repeat Character)
Đề bài: Nhập một ký tự và số n. In ký tự đó n lần trên cùng một dòng.
Problem: Enter a character and number n. Print that character n times on same line.
Example Input/Output
Input:
Enter character: #
Enter n: 6Output:
# # # # # #Hints (Gợi Ý)
- Nhập ký tự bằng input()
- Nhập n
- Vòng lặp n lần in ký tự
Solution (Đáp Án)
pythonchar = input("Enter character: ") n = int(input("Enter n: ")) for i in range(n): print(char, end=" ") print()
Explanation (Giải Thích)
Vietnamese: Lưu ký tự, sau đó vòng lặp in ký tự đó n lần.
English: Store character, then loop prints that character n times.
Tier 2: Intermediate (Trung Cấp) - Exercises 11-20
Cấp độ: Trung bình - Kết hợp vòng lặp với điều kiện
Bài Tập 11: Đếm Số Chẵn (Count Even Numbers)
Đề bài: Nhập n số nguyên. Đếm có bao nhiêu số chẵn.
Problem: Enter n integers. Count how many are even.
Example Input/Output
Input:
Enter count: 5
Numbers: 10, 15, 22, 7, 8Output:
Even count: 3Hints (Gợi Ý)
- Số chẵn: number % 2 == 0
- Khởi tạo biến đếm = 0
- Mỗi số chẵn tăng biến đếm
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) count = 0 for i in range(n): number = int(input("Enter number: ")) if number % 2 == 0: count += 1 print(f"Even count: {count}")
Explanation (Giải Thích)
Vietnamese: Kiểm tra mỗi số bằng modulo %. Nếu chia hết cho 2 thì tăng biến đếm.
English: Check each number using modulo %. If divisible by 2, increment counter.
Bài Tập 12: Tìm Số Lớn Nhất (Find Maximum)
Đề bài: Nhập n số nguyên. Tìm và in số lớn nhất.
Problem: Enter n integers. Find and print the maximum.
Example Input/Output
Input:
Enter count: 4
Numbers: 15, 42, 8, 23Output:
Maximum: 42Hints (Gợi Ý)
- Khởi tạo max_num = float('-inf')
- So sánh mỗi số với max_num
- Cập nhật max_num nếu số lớn hơn
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) max_num = float('-inf') for i in range(n): number = int(input("Enter number: ")) if number > max_num: max_num = number print(f"Maximum: {max_num}")
Explanation (Giải Thích)
Vietnamese: Bắt đầu với giá trị âm vô cùng. Cập nhật khi gặp số lớn hơn.
English: Start with negative infinity. Update when encountering larger number.
Bài Tập 13: Tìm Số Nhỏ Nhất (Find Minimum)
Đề bài: Nhập n số nguyên. Tìm và in số nhỏ nhất.
Problem: Enter n integers. Find and print the minimum.
Example Input/Output
Input:
Enter count: 4
Numbers: 15, 7, 23, 11Output:
Minimum: 7Hints (Gợi Ý)
- Khởi tạo min_num = float('inf')
- So sánh mỗi số với min_num
- Cập nhật min_num nếu số nhỏ hơn
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) min_num = float('inf') for i in range(n): number = int(input("Enter number: ")) if number < min_num: min_num = number print(f"Minimum: {min_num}")
Explanation (Giải Thích)
Vietnamese: Bắt đầu với dương vô cùng. Cập nhật khi gặp số nhỏ hơn.
English: Start with positive infinity. Update when encountering smaller number.
Bài Tập 14: Đếm Số Dương (Count Positive Numbers)
Đề bài: Nhập n số nguyên. Đếm có bao nhiêu số dương (lớn hơn 0).
Problem: Enter n integers. Count how many are positive (greater than 0).
Example Input/Output
Input:
Enter count: 5
Numbers: -3, 7, 0, 12, -5Output:
Positive count: 2Hints (Gợi Ý)
- Số dương: number > 0
- Khởi tạo biến đếm
- Kiểm tra điều kiện và tăng đếm
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) count = 0 for i in range(n): number = int(input("Enter number: ")) if number > 0: count += 1 print(f"Positive count: {count}")
Explanation (Giải Thích)
Vietnamese: Đơn giản kiểm tra number > 0 và đếm.
English: Simply check number > 0 and count.
Bài Tập 15: Đếm Bội Số của 3 (Count Multiples of 3)
Đề bài: Nhập n số nguyên. Đếm có bao nhiêu số chia hết cho 3.
Problem: Enter n integers. Count how many are divisible by 3.
Example Input/Output
Input:
Enter count: 5
Numbers: 9, 10, 15, 7, 21Output:
Count: 3Hints (Gợi Ý)
- Chia hết cho 3: number % 3 == 0
- Đếm các số thỏa điều kiện
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) count = 0 for i in range(n): number = int(input("Enter number: ")) if number % 3 == 0: count += 1 print(f"Count: {count}")
Explanation (Giải Thích)
Vietnamese: Dùng modulo % để kiểm tra chia hết.
English: Use modulo % to check divisibility.
Bài Tập 16: Phân Loại Số (Categorize Numbers)
Đề bài: Nhập n số. Đếm có bao nhiêu số âm, số 0, và số dương.
Problem: Enter n numbers. Count negative, zero, and positive numbers.
Example Input/Output
Input:
Enter count: 5
Numbers: -3, 0, 7, -5, 12Output:
Negative: 2
Zero: 1
Positive: 2Hints (Gợi Ý)
- Dùng 3 biến đếm
- if-elif-else để phân loại
- In cả 3 kết quả
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) negative = 0 zero = 0 positive = 0 for i in range(n): number = int(input("Enter number: ")) if number < 0: negative += 1 elif number == 0: zero += 1 else: positive += 1 print(f"Negative: {negative}") print(f"Zero: {zero}") print(f"Positive: {positive}")
Explanation (Giải Thích)
Vietnamese: Dùng if-elif-else để phân loại và đếm từng loại.
English: Use if-elif-else to categorize and count each type.
Bài Tập 17: Tính Trung Bình (Calculate Average)
Đề bài: Nhập n số. Tính và in trung bình cộng.
Problem: Enter n numbers. Calculate and print average.
Example Input/Output
Input:
Enter count: 4
Numbers: 10, 20, 30, 40Output:
Average: 25.0Hints (Gợi Ý)
- Tính tổng các số
- Chia tổng cho n
- In với 2 chữ số thập phân
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) total = 0 for i in range(n): number = int(input("Enter number: ")) total += number average = total / n print(f"Average: {average:.1f}")
Explanation (Giải Thích)
Vietnamese: Cộng dồn tổng, sau đó chia cho n để có trung bình.
English: Sum all numbers, then divide by n for average.
Bài Tập 18: In Số Chẵn (Print Even Numbers)
Đề bài: Nhập n số. Chỉ in ra các số chẵn.
Problem: Enter n numbers. Print only even numbers.
Example Input/Output
Input:
Enter count: 5
Numbers: 10, 15, 22, 7, 8Output:
10
22
8Hints (Gợi Ý)
- Kiểm tra number % 2 == 0
- Chỉ in khi số chẵn
- Không cần biến đếm
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) if number % 2 == 0: print(number)
Explanation (Giải Thích)
Vietnamese: Nhập số, kiểm tra chẵn, in ngay nếu đúng.
English: Input number, check if even, print immediately if true.
Bài Tập 19: Đếm Số Lẻ (Count Odd Numbers)
Đề bài: Nhập n số. Đếm có bao nhiêu số lẻ.
Problem: Enter n numbers. Count how many are odd.
Example Input/Output
Input:
Enter count: 5
Numbers: 10, 15, 22, 7, 8Output:
Odd count: 2Hints (Gợi Ý)
- Số lẻ: number % 2 != 0
- Hoặc number % 2 == 1
- Đếm các số thỏa điều kiện
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) count = 0 for i in range(n): number = int(input("Enter number: ")) if number % 2 != 0: count += 1 print(f"Odd count: {count}")
Explanation (Giải Thích)
Vietnamese: Kiểm tra số lẻ bằng modulo khác 0.
English: Check odd using modulo not equal 0.
Bài Tập 20: Tổng Số Dương (Sum Positive Numbers)
Đề bài: Nhập n số. Tính tổng của CHỈ các số dương.
Problem: Enter n numbers. Calculate sum of ONLY positive numbers.
Example Input/Output
Input:
Enter count: 5
Numbers: -3, 7, -5, 12, 0Output:
Sum: 19Hints (Gợi Ý)
- Khởi tạo tổng = 0
- Chỉ cộng khi number > 0
- Bỏ qua số âm và số 0
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) total = 0 for i in range(n): number = int(input("Enter number: ")) if number > 0: total += number print(f"Sum: {total}")
Explanation (Giải Thích)
Vietnamese: Chỉ cộng vào tổng khi số dương. Bỏ qua số âm và 0.
English: Only add to sum when positive. Skip negative and 0.
Tier 3: Advanced (Nâng Cao) - Exercises 21-30
Cấp độ: Nâng cao - Vòng lặp lồng nhau, điều kiện lồng nhau
Bài Tập 21: Tính Điểm Chữ (Grade Calculator)
Đề bài: Nhập n điểm (0-100). Với mỗi điểm, in điểm chữ: A (90-100), B (80-89), C (70-79), D (60-69), F (<60).
Problem: Enter n scores (0-100). For each, print letter grade: A (90-100), B (80-89), C (70-79), D (60-69), F (<60).
Example Input/Output
Input:
Enter count: 3
Scores: 95, 78, 55Output:
A
C
FHints (Gợi Ý)
- Dùng if-elif-else
- Kiểm tra từ cao xuống thấp
- In điểm chữ cho mỗi điểm
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): score = int(input("Enter score: ")) if score >= 90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F")
Explanation (Giải Thích)
Vietnamese: Chuỗi if-elif kiểm tra điểm từ cao xuống thấp.
English: If-elif chain checks score from high to low.
Bài Tập 22: Tính BMI (BMI Calculator)
Đề bài: Nhập cân nặng (kg) và chiều cao (m) của n người. Tính BMI và phân loại: Underweight (<18.5), Normal (18.5-24.9), Overweight (25-29.9), Obese (>=30).
Problem: Enter weight (kg) and height (m) of n people. Calculate BMI and categorize: Underweight (<18.5), Normal (18.5-24.9), Overweight (25-29.9), Obese (>=30).
Example Input/Output
Input:
Enter count: 2
Person 1: 70kg, 1.75m
Person 2: 90kg, 1.70mOutput:
Normal
ObeseHints (Gợi Ý)
- BMI = weight / (height * height)
- Mỗi người nhập 2 giá trị
- Dùng if-elif-else phân loại
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): weight = float(input("Weight (kg): ")) height = float(input("Height (m): ")) bmi = weight / (height * height) if bmi < 18.5: print("Underweight") elif bmi < 25: print("Normal") elif bmi < 30: print("Overweight") else: print("Obese")
Explanation (Giải Thích)
Vietnamese: Tính BMI rồi phân loại theo ngưỡng.
English: Calculate BMI then categorize by thresholds.
Bài Tập 23: Tam Giác Vuông (Right Triangle)
Đề bài: Nhập số dòng n. In tam giác vuông bằng sao.
Problem: Enter rows n. Print right triangle with stars.
Example Input/Output
Input:
Enter n: 5Output:
*
* *
* * *
* * * *
* * * * *Hints (Gợi Ý)
- Vòng lặp ngoài: dòng
- Vòng lặp trong: sao
- Dòng i có i sao
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(1, n + 1): for j in range(i): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp lồng cơ bản tạo tam giác.
English: Basic nested loop creates triangle.
Bài Tập 24: Kim Tự Tháp Số Đối Xứng (Symmetric Number Pyramid)
Đề bài: Nhập n. In kim tự tháp số: dòng 1 là '1', dòng 2 là '121', dòng 3 là '12321'.
Problem: Enter n. Print number pyramid: row 1 is '1', row 2 is '121', row 3 is '12321'.
Example Input/Output
Input:
Enter n: 4Output:
1
121
12321
1234321Hints (Gợi Ý)
- Mỗi dòng có 2 phần: tăng và giảm
- Tăng: 1 đến i
- Giảm: i-1 về 1
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(1, n + 1): # Ascending for j in range(1, i + 1): print(j, end="") # Descending for j in range(i - 1, 0, -1): print(j, end="") print()
Explanation (Giải Thích)
Vietnamese: 2 vòng lặp mỗi dòng: tăng và giảm.
English: 2 loops per row: ascending and descending.
Bài Tập 25: Hình Vuông (Square Pattern)
Đề bài: Nhập kích thước n. In hình vuông đặc bằng sao (n x n).
Problem: Enter size n. Print solid square with stars (n x n).
Example Input/Output
Input:
Enter n: 4Output:
* * * *
* * * *
* * * *
* * * *Hints (Gợi Ý)
- Vòng ngoài: n dòng
- Vòng trong: n sao mỗi dòng
- Đơn giản nhất trong các pattern
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(n): for j in range(n): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp lồng đơn giản. Mỗi dòng n sao.
English: Simple nested loop. Each row n stars.
Bài Tập 26: Chuyển Đổi Nhiệt Độ (Temperature Converter)
Đề bài: Nhập n nhiệt độ Celsius. Chuyển sang Fahrenheit và phân loại: Cold (<50°F), Moderate (50-80°F), Hot (>80°F).
Problem: Enter n Celsius temperatures. Convert to Fahrenheit and categorize: Cold (<50°F), Moderate (50-80°F), Hot (>80°F).
Example Input/Output
Input:
Enter count: 3
Temps: 0, 20, 35Output:
32.0°F - Cold
68.0°F - Moderate
95.0°F - HotHints (Gợi Ý)
- F = C * 9/5 + 32
- Sau khi chuyển đổi, phân loại
- In cả nhiệt độ và loại
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): celsius = float(input("Enter Celsius: ")) fahrenheit = celsius * 9/5 + 32 if fahrenheit < 50: category = "Cold" elif fahrenheit <= 80: category = "Moderate" else: category = "Hot" print(f"{fahrenheit:.1f}°F - {category}")
Explanation (Giải Thích)
Vietnamese: Chuyển đổi nhiệt độ rồi phân loại.
English: Convert temperature then categorize.
Bài Tập 27: Đếm Theo Khoảng (Count by Range)
Đề bài: Nhập n số dương. Đếm có bao nhiêu số trong 0-10, 11-20, và >20.
Problem: Enter n positive numbers. Count how many in 0-10, 11-20, and >20.
Example Input/Output
Input:
Enter count: 5
Numbers: 5, 15, 25, 8, 22Output:
0-10: 2
11-20: 1
>20: 2Hints (Gợi Ý)
- 3 biến đếm cho 3 khoảng
- Dùng if-elif-else
- In cả 3 kết quả
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) range1 = 0 range2 = 0 range3 = 0 for i in range(n): number = int(input("Enter number: ")) if number <= 10: range1 += 1 elif number <= 20: range2 += 1 else: range3 += 1 print(f"0-10: {range1}") print(f"11-20: {range2}") print(f">20: {range3}")
Explanation (Giải Thích)
Vietnamese: Phân loại vào 3 khoảng và đếm.
English: Categorize into 3 ranges and count.
Bài Tập 28: Kim Tự Tháp Đảo Ngược (Inverted Pyramid)
Đề bài: Nhập n. In kim tự tháp đảo ngược bằng sao.
Problem: Enter n. Print inverted pyramid with stars.
Example Input/Output
Input:
Enter n: 5Output:
* * * * *
* * * *
* * *
* *
*Hints (Gợi Ý)
- Đếm ngược từ n về 1
- Dòng i có i sao
- range(n, 0, -1)
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(n, 0, -1): for j in range(i): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Đếm ngược tạo kim tự tháp đảo.
English: Count down creates inverted pyramid.
Bài Tập 29: Xác Thực Số Dương (Validate Positive)
Đề bài: Nhập n số. Nếu số âm, yêu cầu nhập lại cho đến khi dương hoặc 0. Cuối cùng in tổng.
Problem: Enter n numbers. If negative, ask to re-enter until positive or 0. Finally print sum.
Example Input/Output
Input:
Enter count: 3
Number 1: 10
Number 2: -5
Invalid! Try again: 15
Number 3: 20Output:
Sum: 45Hints (Gợi Ý)
- Vòng for cho n số
- Vòng while cho mỗi số nếu âm
- Cộng số hợp lệ vào tổng
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) total = 0 for i in range(n): number = int(input(f"Number {i+1}: ")) while number < 0: number = int(input("Invalid! Try again: ")) total += number print(f"Sum: {total}")
Explanation (Giải Thích)
Vietnamese: Kết hợp for và while để xác thực input.
English: Combine for and while to validate input.
Bài Tập 30: Hình Thoi Đơn Giản (Simple Diamond)
Đề bài: Nhập n (số lẻ). In hình thoi bằng sao: nửa trên tăng, nửa dưới giảm.
Problem: Enter n (odd). Print diamond with stars: upper half increases, lower half decreases.
Example Input/Output
Input:
Enter n: 5Output:
*
* * *
* * * * *
* * *
*Hints (Gợi Ý)
- Chia 2 phần: trên và dưới
- Nửa trên: 1, 3, 5 sao
- Nửa dưới: 3, 1 sao
Solution (Đáp Án)
pythonn = int(input("Enter n (odd): ")) mid = (n + 1) // 2 # Upper half for i in range(1, mid + 1): for j in range(2 * i - 1): print("*", end=" ") print() # Lower half for i in range(mid - 1, 0, -1): for j in range(2 * i - 1): print("*", end=" ") print()
Explanation (Giải Thích)
Vietnamese: Chia thành 2 tam giác: tăng và giảm.
English: Split into 2 triangles: increase and decrease.
Tier 4: Complex (Phức Tạp) - Exercises 31-40
Cấp độ: Phức tạp - Nhiều cấp độ lồng nhau, thuật toán
Bài Tập 31: Kiểm Tra Số Nguyên Tố (Prime Number Checker)
Đề bài: Nhập n số nguyên dương. Với mỗi số, kiểm tra có phải số nguyên tố không.
Problem: Enter n positive integers. For each, check if it's prime.
Example Input/Output
Input:
Enter count: 3
Numbers: 7, 10, 13Output:
Prime
Not Prime
PrimeHints (Gợi Ý)
- Số nguyên tố > 1, chỉ chia hết cho 1 và chính nó
- Kiểm tra từ 2 đến căn bậc 2
- Nếu chia hết cho bất kỳ số nào, không phải nguyên tố
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) if number <= 1: is_prime = False else: is_prime = True for j in range(2, int(number ** 0.5) + 1): if number % j == 0: is_prime = False break print("Prime" if is_prime else "Not Prime")
Explanation (Giải Thích)
Vietnamese: Vòng lặp kiểm tra ước từ 2 đến căn n.
English: Loop checks divisors from 2 to sqrt(n).
Bài Tập 32: Tìm Ước Số (Find Divisors)
Đề bài: Nhập n số. Với mỗi số, tìm và in tất cả ước số.
Problem: Enter n numbers. For each, find and print all divisors.
Example Input/Output
Input:
Enter count: 2
Numbers: 12, 7Output:
Divisors of 12: 1 2 3 4 6 12
Divisors of 7: 1 7Hints (Gợi Ý)
- Ước số: số chia hết
- Kiểm tra từ 1 đến n
- In các số chia hết
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) print(f"Divisors of {number}:", end=" ") for j in range(1, number + 1): if number % j == 0: print(j, end=" ") print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp lồng kiểm tra từng số xem có phải ước không.
English: Nested loop checks each number if it's a divisor.
Bài Tập 33: Tính GCD (Thuật Toán Euclid) (GCD Calculator (Euclidean Algorithm))
Đề bài: Nhập n cặp số. Với mỗi cặp, tính GCD (Ước Chung Lớn Nhất).
Problem: Enter n pairs of numbers. For each pair, calculate GCD (Greatest Common Divisor).
Example Input/Output
Input:
Enter pairs: 3
Pair 1: 48, 18
Pair 2: 100, 25
Pair 3: 17, 13Output:
GCD: 6
GCD: 25
GCD: 1Hints (Gợi Ý)
- GCD(a, b) = GCD(b, a % b)
- Lặp cho đến khi b = 0
- Kết quả là a
Solution (Đáp Án)
pythonn = int(input("Enter pairs: ")) for i in range(n): a = int(input("First number: ")) b = int(input("Second number: ")) while b != 0: temp = b b = a % b a = temp print(f"GCD: {a}")
Explanation (Giải Thích)
Vietnamese: Thuật toán Euclid dùng vòng while và modulo.
English: Euclidean algorithm uses while loop and modulo.
Bài Tập 34: Dãy Fibonacci (Fibonacci Sequence)
Đề bài: Nhập n test case. Với mỗi test, nhập k và in k số Fibonacci đầu tiên.
Problem: Enter n test cases. For each, enter k and print first k Fibonacci numbers.
Example Input/Output
Input:
Enter tests: 2
Test 1, k: 5
Test 2, k: 7Output:
0 1 1 2 3
0 1 1 2 3 5 8Hints (Gợi Ý)
- F(0) = 0, F(1) = 1
- F(n) = F(n-1) + F(n-2)
- Dùng 2 biến lưu 2 số trước
Solution (Đáp Án)
pythonn = int(input("Enter tests: ")) for i in range(n): k = int(input(f"Test {i+1}, k: ")) if k >= 1: a, b = 0, 1 print(a, end=" ") if k >= 2: print(b, end=" ") for j in range(2, k): c = a + b print(c, end=" ") a, b = b, c print()
Explanation (Giải Thích)
Vietnamese: Dùng 2 biến để tính số tiếp theo.
English: Use 2 variables to calculate next number.
Bài Tập 35: Năm Nhuận (Leap Year)
Đề bài: Nhập n năm. Kiểm tra mỗi năm có phải năm nhuận không.
Problem: Enter n years. Check if each is a leap year.
Example Input/Output
Input:
Enter count: 4
Years: 2000, 1900, 2020, 2021Output:
Leap
Not Leap
Leap
Not LeapHints (Gợi Ý)
- Chia hết cho 4 NHƯNG không chia hết cho 100
- HOẶC chia hết cho 400
- Dùng toán tử logic
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): year = int(input("Enter year: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print("Leap") else: print("Not Leap")
Explanation (Giải Thích)
Vietnamese: Điều kiện phức tạp với nhiều toán tử logic.
English: Complex condition with multiple logical operators.
Bài Tập 36: Tam Giác Floyd (Floyd's Triangle)
Đề bài: Nhập n dòng. In tam giác Floyd (số tự nhiên liên tiếp).
Problem: Enter n rows. Print Floyd's Triangle (consecutive natural numbers).
Example Input/Output
Input:
Enter n: 5Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15Hints (Gợi Ý)
- Số tăng liên tục, không reset
- Dòng i có i số
- Biến num ở ngoài vòng lặp
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) num = 1 for i in range(1, n + 1): for j in range(i): print(num, end=" ") num += 1 print()
Explanation (Giải Thích)
Vietnamese: Biến num tăng liên tục qua các dòng.
English: Variable num increments continuously across rows.
Bài Tập 37: Tam Giác Pascal (Pascal's Triangle)
Đề bài: Nhập n dòng. In tam giác Pascal.
Problem: Enter n rows. Print Pascal's Triangle.
Example Input/Output
Input:
Enter n: 5Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1Hints (Gợi Ý)
- Công thức: C(n, k) = C(n-1, k-1) + C(n-1, k)
- Hoặc tính nhanh từng phần tử
- Viền luôn là 1
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) for i in range(n): num = 1 for j in range(i + 1): print(num, end=" ") num = num * (i - j) // (j + 1) print()
Explanation (Giải Thích)
Vietnamese: Dùng công thức tính nhanh để tránh tính giai thừa.
English: Use fast formula to avoid calculating factorials.
Bài Tập 38: Số Hoàn Hảo (Perfect Number)
Đề bài: Nhập n số. Kiểm tra mỗi số có phải số hoàn hảo không (tổng ước bằng chính nó).
Problem: Enter n numbers. Check if each is perfect (sum of divisors equals itself).
Example Input/Output
Input:
Enter count: 3
Numbers: 6, 28, 12Output:
Perfect
Perfect
Not PerfectHints (Gợi Ý)
- Ước thực sự: không bao gồm chính nó
- Tìm ước từ 1 đến n-1
- So sánh tổng với số ban đầu
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) sum_divisors = 0 for j in range(1, number): if number % j == 0: sum_divisors += j if sum_divisors == number: print("Perfect") else: print("Not Perfect")
Explanation (Giải Thích)
Vietnamese: Tính tổng ước rồi so sánh với số gốc.
English: Calculate sum of divisors then compare with original.
Bài Tập 39: Giả Thuyết Collatz (Collatz Conjecture)
Đề bài: Nhập n số. Với mỗi số, áp dụng quy tắc Collatz (chẵn chia 2, lẻ nhân 3 cộng 1) cho đến khi về 1. In số bước.
Problem: Enter n numbers. For each, apply Collatz rule (even divide by 2, odd multiply by 3 add 1) until reaching 1. Print steps.
Example Input/Output
Input:
Enter count: 3
Numbers: 6, 10, 27Output:
Steps: 8
Steps: 6
Steps: 111Hints (Gợi Ý)
- Vòng while cho đến khi = 1
- Chẵn: n = n // 2
- Lẻ: n = n * 3 + 1
- Đếm số bước
Solution (Đáp Án)
pythonn = int(input("Enter count: ")) for i in range(n): number = int(input("Enter number: ")) steps = 0 while number != 1: if number % 2 == 0: number = number // 2 else: number = number * 3 + 1 steps += 1 print(f"Steps: {steps}")
Explanation (Giải Thích)
Vietnamese: Vòng while áp dụng quy tắc cho đến khi về 1.
English: While loop applies rule until reaching 1.
Bài Tập 40: Số Armstrong (Armstrong Number)
Đề bài: Nhập số n. Tìm và in tất cả số Armstrong từ 1 đến n. (Tổng các chữ số mũ k = chính nó, k là số chữ số).
Problem: Enter n. Find and print all Armstrong numbers from 1 to n. (Sum of digits^k equals itself, k is digit count).
Example Input/Output
Input:
Enter n: 1000Output:
Armstrong: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407Hints (Gợi Ý)
- Lặp từ 1 đến n
- Đếm số chữ số k
- Tính tổng chữ số mũ k
- So sánh với số gốc
Solution (Đáp Án)
pythonn = int(input("Enter n: ")) print("Armstrong:", end=" ") first = True for num in range(1, n + 1): k = len(str(num)) sum_powers = 0 temp = num while temp > 0: digit = temp % 10 sum_powers += digit ** k temp //= 10 if sum_powers == num: if not first: print(",", end=" ") print(num, end="") first = False print()
Explanation (Giải Thích)
Vietnamese: Vòng lặp chính kiểm tra từng số. Vòng lồng tính tổng lũy thừa.
English: Main loop checks each number. Nested loop calculates power sum.
Conclusion (Kết Luận)
Chúc mừng! Bạn đã hoàn thành 40 bài tập về vòng lặp và điều kiện. Những kỹ năng này là nền tảng quan trọng cho lập trình Python.
Bước tiếp theo: Học về hàm (Functions) và cấu trúc dữ liệu (Data Structures).