Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

A function that takes numbers in list < 5 Python

So I'm working on a little project to make a function that takes an input, puts it in a list and spits out a list of numbers less than 5 in the list. I can do this little project easily outside a function but am having trouble making a function.

It keeps saying: if num < 5: TypeError: '<' not supported between instances of 'str' and 'int'

However when I change either choice to int of num to int it still gets an error. Any way I can fix this?

Also a weird extra question: if I were to test numbers inside a list without the for loop and print the list after, what would that look like?

def less_than ():
    choice_list = []
    while True:
        print ("Please pick a number")
        print ("If you don't want anymore numbers, press Enter")
        choice = input()
        choice_list.append(choice)
        if choice == '':
            break
    for num in choice_list:
        if num < 5:
            print (num)
print (less_than())

1 Answer

When you call input(), it returns a string. You are appending the input to a list, therefore the list is full of strings. When you go through the list and compare it to the number five, you are really comparing strings to numbers, and Python throws it hands up with an error. (Python is dumb, and cannot compare strings and numbers!)

Solution: Convert the strings to ints. Try using the function (appropriately) named int() to convert strings to integers (aka numbers).

As for your "weird" question, which is in fact a perfectly natural question to ask, the solution is to check immediately after receiving input. For example...

numbers = []
print("Press enter to quit.")
while True:
    number = input("Enter a number:  ")
    if number == '':
        break
    if int(number) < 5:
        numbers.append(number)
print(numbers)

Wow it's so simple and makes sense. Thanks so much!

No problem :)