Python Practice › If-Else Programs › Program 49
Which group of ten a number belongs to
Write a Python program that splits 1-100 into 10 groups (1-10, 11-20, … 91-100) and finds which group a number belongs to, using nested if-else.
Input
36, 100, 1, 105
Output
36 belongs to the 4th group 100 belongs to the 10th group 1 belongs to the 1st group 105 is outside 1-100
Approach
- Check the range is valid with the outer if.
- Calculate the group with
(n - 1) // 10 + 1inside it.
Solution
def group_of(n): if 1 <= n <= 100: group = (n - 1) // 10 + 1 if group == 1: suffix = "st" elif group == 2: suffix = "nd" elif group == 3: suffix = "rd" else: suffix = "th" return f"{n} belongs to the {group}{suffix} group" else: return f"{n} is outside 1-100" for n in [36, 100, 1, 105]: print(group_of(n))Output
36 belongs to the 4th group 100 belongs to the 10th group 1 belongs to the 1st group 105 is outside 1-100
Line by line
Line 2
The outer check rejects values outside the range.
Line 3
Subtracting 1 makes 1-10 map to 0, 11-20 to 1 and so on; adding 1 gives the group number.
Lines 4-11
The inner if-else picks the English ordinal suffix.
Learn the concept
New to this topic? Read the lesson, then come back.