Search code examples
pythonlistvalueerror

What I am doing wrong? Output values below an amount


Here is the question I am working on:

Write a program that first gets a list of integers from input. The last value of the input represents a threshold. Output all integers less than or equal to that threshold value. Do not include the threshold value in the output.

For simplicity, follow each number output by a comma, including the last one.

Ex: If the input is:

50 60 140 200 75 100

the output should be:

50,60,75,

My code is:

n = int(input())
lst = []
for i in range(n):
    lst.append(int(input()))
threshold = int(input())
for i in range(n):
    if list[i] <= threshold:
        print(last[i],end=',')

I keep getting an error, and I can't seem to know why:

ValueError: invalid literal for int() with base 10: '50 60 140 200 75 100' 

Solution

  • This is a clean way to do this:

    # import numbers separated with a space
    n = input()
    n = n.split(' ')
    n = [int(x) for x in n]  # <-- converts strings to integers
    
    # threshold is the last number
    threshold = n[-1]
    
    # get the result
    result = [x for x in n if x < threshold]
    print(result)
    

    the result:

    [50, 60, 75]