Home > Mobile >  Counting and separating ages by groups in append list (user input) (python)
Counting and separating ages by groups in append list (user input) (python)

Time:07-03

I've trying to figure out this myself but I cannot get the results I want, and I've been unable to find the right answer looking through the internet. I have a piece of code that ask the user 10 ages and stores them in an append list, the problem is I can separate them by ages but I don't know how to count the amount by age group. I tried looking for documentation but most of it are examples with a list with known values. Can anyone give me some advice? This is my code so far:

age = []
for i in range (10):
    ag = int (input("Write your age"))
    age.append(ag)
print ("The number of kids are: ")
for i in range (10):
    if age [i] < 12:
        print (age [i])
print ("The number of teenagers are: ")
for i in range (10):
    if age [i] >=12 and age [i] < 17:
        print (age [i])
print ("The number of adults are: ")
for i in range (10):
    if age [i] >= 18:
        print (age [i])

CodePudding user response:

once you've collected your ages, you could filter them into sub-lists, something like:

ages = [5, 10, 17, 18, 20, 30, 50]

kids = [a for a in ages if a <= 12]
teens = [a for a in ages if a > 12 and a < 20]
adults = a for a in ages if a >= 20]

# print summaries
print(f'there are {len(kids)} kids: {kids}')
print(f'there are {len(teens)} teens: {teens}')

The above example is using a feature of python called list comprehensions [value for value in list (if condition)]

You could also loop over the items explicitly and print/populate values if you wanted:

kids = []
teens = []
...
for age in ages:
    if age < 13:
        kids.append(age)
    elif age < 20:
        teens.append(age)
    else:
        ...
print('teens are', teens)

CodePudding user response:

Use only one loop, the one that builds the data, at the same time increment counter for each category

ages = []
kids, teen, adult = 0, 0, 0

for i in range(10):
    age = int(input("Write your age"))
    ages.append(age)

    if age < 12:
        kids  = 1
    elif age <= 17:
        teen  = 1
    else:
        adult  = 1

print("The number of kids is: ", kids)
print("The number of teenagers is: ", teen)
print("The number of adults is: ", adult)
  • Related