简体   繁体   中英

Python - TypeError: '<' not supported between instances of 'int' and 'list'

I'm doing a small task in Python. I have to categorizes age into six different categories, based on the age ranges specified in the question. If the age is less than 18, the code prints "Category: Under 18". If the age is between 18 and 24, the code prints "Category: 18-24", and so on.

Here's my code:

Age_Group = [18,24,34,44,54,64]


if Age_Group < 18:
    print("Category: Under 18")

elif Age_Group  >= 18 and Age_Group <= 24:
    print("Category: 18-24")

elif Age_Group  >= 25 and Age_Group  <= 34:
    print("Category: 25-34")

elif Age_Group  >= 35 and Age_Group  <= 44:
    print("Category: 35-44")

elif Age_Group  >= 45 and Age_Group  <= 54:
    print("Category: 45-54")

elif Age_Group  >= 55:
    print("Category: 55 and over")

When I executed the code, I got 'TypeError' message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-166-8814d798b4aa> in <module>
      2 
      3 
----> 4 if Age_Group < 18:
      5     print("Category: Under 18")
      6 

TypeError: '<' not supported between instances of 'list' and 'int'

Can anyone help me with this?

You need to access each element of the list and perform the comparison, instead of using <=> operators between list and integer value:

Age_Group = [18,24,34,44,54,64]

for i in Age_Group:
    print(f"Age {i}")
    if i < 18:
        print("Category: Under 18")
    
    elif i  >= 18 and i <= 24:
        print("Category: 18-24")
    
    elif i  >= 25 and i  <= 34:
        print("Category: 25-34")
    
    elif i  >= 35 and i  <= 44:
        print("Category: 35-44")
    
    elif i  >= 45 and i  <= 54:
        print("Category: 45-54")
    
    elif i  >= 55:
        print("Category: 55 and over")

Output:

Age 18
Category: 18-24
Age 24
Category: 18-24
Age 34
Category: 25-34
Age 44
Category: 35-44
Age 54
Category: 45-54
Age 64
Category: 55 and over

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM