logical operator inside for loop, not working

Viewed 92

I'm currently studying Python and I've been stuck at this problem for a few hours now. I was given a task to take user input of numbers and split those numbers, and display numbers greater than 3, example:

Input: 12345
Output: 4
        5

I had some progress with splitting those numbers, and now I'm at this part where it's supposed to figure out if the number is greater than 3 but I keep on getting "TypeError: '>' not supported between instances of 'list' and 'int' "

Anyway, here's my code:

num_input = list(input('Enter number: '))

for i in num_input:
    if num_input > 3:
        print(i)
3 Answers

Ok, it should be:

num_input = input('Enter number: ')

for i in num_input:
    if int(i) > 3:
        print(i)

Basically, you just get a single char from the string 12345 at a time and convert it to an int. Then you can compare it to 3 normally.

If you need a shorter version:

num_input = input('Enter number: ')

print([int(i) for i in num_input if int(i) > 3])

Which you output: [4, 5] if you input 123456

You have to make the objects inside the list as integers and then only you can compare them to an integer, in your case greater than three. This should work

num_input = list(map(int,input().split()))

for i in num_input:
    if i > 3:
        print(i)

This allows to input multiple values in a single line

You don't need the list(). Your input is string, you can iterate through every character of string, cast it to int and then compare:

num_input = input('Enter number: ')

for i in num_input:
    if int(i) > 3:
        print(i)
Related