Viết chương trình Python để đếm số dương và số âm trong Tuple bằng cách sử dụng phạm vi vòng lặp for. Điều kiện if [if [posngTuple[i] > = 0]] kiểm tra xem mục Tuple lớn hơn hoặc bằng 0. Nếu Đúng, chúng tôi thêm một vào số Tuple Tích cực; nếu không [tNegativeCount = tNegativeCount + 1], hãy thêm một vào giá trị số Tuple Phủ định.
# Count Positive and Negative Numbers posngTuple = [3, -22, -44, 19, -99, -37, 4, 11, -89] print["Positive and Negative Tuple Items = ", posngTuple] tPositiveCount = tNegativeCount = 0 for i in range[len[posngTuple]]: if [posngTuple[i] >= 0]: tPositiveCount = tPositiveCount + 1 else: tNegativeCount = tNegativeCount + 1 print["The Count of Positive Numbers in posngTuple = ", tPositiveCount] print["The Count of Negative Numbers in posngTuple = ", tNegativeCount]Trong ví dụ Tích cực và Phủ định Python này, chúng tôi đã sử dụng vòng lặp for [cho pntup trong posngTuple] để lặp lại các giá trị tuple thực tế và kiểm tra xem chúng lớn hơn hay bằng 0.
Chương trình Python để đếm Tích cực và Phủ định trong Tuple bằng cách sử dụng Vòng lặp While.
# Count of Tuple Positive and Negative Numbers posngTuple = [11, -22, -33, 44, 55, -66, -77, 0, -99] print["Positive and Negative Tuple Items = ", posngTuple] tPositiveCount = tNegativeCount = 0 i = 0 while [i < len[posngTuple]]: if[posngTuple[i] >= 0]: tPositiveCount = tPositiveCount + 1 else: tNegativeCount = tNegativeCount + 1 i = i + 1 print["The Count of Positive Numbers in posngTuple = ", tPositiveCount] print["The Count of Negative Numbers in posngTuple = ", tNegativeCount]Positive and Negative Tuple Items = [11, -22, -33, 44, 55, -66, -77, 0, -99] The Count of Positive Numbers in posngTuple = 4 The Count of Negative Numbers in posngTuple = 5Trong ví dụ Python Tuple này, chúng tôi đã tạo một hàm trả về số lượng số Dương và Số âm.