I am trying to take a list that a user inputs, filter and sort in ascending order but only for the non-negative numbers. I thought I understood how to do this but it will not work with my logic.
my_list = [] n = int(input()) for i in range(0, n): element = int(input()) if element > 0: my_list.append(element) my_list.sort() print(my_list)
Here is the error I receive: ValueError: invalid literal for int() with base 10: ’10 -7 4 39 -6 12 2′ It doesn’t like line 2
Advertisement
Answer
You have to put the lenght of the array into n and then use the i do define the element:
my_list = [] n = len(input().split()) for i in range(0, n): element = int(input().split()[i]) if element > 0: my_list.append(element) my_list.sort() print(my_list)
print:
[2, 4, 10, 12, 39]
EDIT: The upper version was tested and works with Py 3.8.2
This is working also on https://ideone.com/rDw1w6#stdin using Py 3.7.3
my_list = [] my_string_array = input().split() n = len(my_string_array) for i in range(0, n): element = int(my_string_array[i]) if element > 0: my_list.append(element) my_list.sort() print(my_list)