Reputation: 1
I am trying to print any number that is great than n, which is 5 in this case. It is only printing 6 and 7. I am not sure what I am doing wrong. This is my code. I am looping through the array and testing if i is greater then n (5)
list = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
filter_list (list, n)
def filter_list (list, n):
` `for i in range(len(list)):
` `if list[i] > n:
` `print (list[i])
the outcome is only 6, 7.
Its not 6, 7, 8, 9
which is what I would like it
It doesnt print the desired outcome
Upvotes: 0
Views: 44
Reputation: 39
Your code is working if you give indent before if statement
list = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
def filter_list (list, n):
for i in range(len(list)):
if list[i] > n:
print (list[i])
filter_list (list, n)
Or you can try this code :
list1 = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
for i in list1 :
if i > n:
print(I)
Hope this will help you :)
Upvotes: 1
Reputation:
Your code is completely fine, if you fix your intent.
list = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
def filter_list (list, n):
for i in range(len(list)):
if list[i] > n:
print (list[i],end =' ')
print(filter_list (list, n))
Output: 6 7 8 9
And you don’t need to call a function. If we use list compression we can increase speed and code readability 👩💻
list = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
print(list(i for i in List if i > n))
Upvotes: 0
Reputation: 4092
For me your code working fine just fix the indent. Just adding end ''
at print to print on same line.
list = [2, 3, 4, 5, 6, 7, 8, 9]
n = 5
def filter_list (list, n):
for i in range(len(list)):
if list[i] > n:
print (list[i],end =' ')
filter_list (list, n)
Gives #
6 7 8 9
Upvotes: 0