0
Display numbers divisible by 5 from a list
def divisiable_by_5(list1): print("Given list",list1) if list1 % 5==0: #tried int(list1) still not running print(list1) # not running x=[5,12,14,18,20,25,10] print("The list is",divisiable_by_5(x))
18 Antworten
+ 3
You need to loop through each value in the list and check if that value is divisible by 5, not the actual list variable, like this
for num in list1:
if num % 5 == 0:
print(num)
+ 2
Amol Bhandekar
Why did you return inside loop?
Do you know after returning something further execution will stop there?
+ 2
print(list(filter(lambda n:n%5==0, [1,5,10,6])))
output: [5, 10]
+ 1
Amol Bhandekar
He has already done using for loop check his previous reply.
+ 1
Amol Bhandekar
Do you have any problem to understand answer given by other people?
See his previous reply he has already shared code.
And you are getting only 5 because you have returned inside loop which will stop to execute further task after returning first value which is 5.
+ 1
Thanks all
@AJ and Jaya understood..
I have tried this new:-
list2=[]
def divisiable_by_5(list1):
print("Given list",list1)
for i in x:
if i%5==0:
list2.append(i)
x=[5,18,155,18,20,25,10]
divisiable_by_5(x)
print("The list is",list2)
+ 1
It is possible tu use list comprehension...[x for x in list if x%5==0]
+ 1
list1_res=[x for x in list1 if x%5==0]
0
Thanks for quick response but I need using function
0
def divisiable_by_5(list1):
print("Given list",list1)
for num in list1:
if num % 5==0: #you cant compare total list , use a loop for each element
print(num)
x=[5,12,14,18,20,25,10]
print("The list divisables are :")
divisiable_by_5(x)
edit:
Amol Bhandekar
by function means how? explain more a bit!!
0
Hey Jaya, in the same code how to do..
already I used function function name is #def divisiable_by_5
0
So is that the answer, you are looking, which I also posted ? or anything else you are looking?
0
tell me what to do or U can modify the same code using loop
0
I already posted code with removed error and using a loop to find divisable_numbers by 5..
0
tried but not showing correct output:-
def divisiable_by_5(list1):
print("Given list",list1)
for i in list1:
if i%5==0:
return i
x=[5,12,14,18,20,25,10]
print("The list is",divisiable_by_5(x))
0
What is your expected output? Amol Bhandekar
your code return only 5.
my code returns all numbers divisable by 5 from list : 5 20 25 10
0
Hey Jay u have given the correct output
Excepted output is :-5 20 25 10
but my code is giving only 5
please share your code if possible
0
def divisiable_by_5(list1):
print("Given list",list1)
for num in list1:
if num % 5==0: #
print(num)
x=[5,12,14,18,20,25,10]
print("The list divisables are :")
divisiable_by_5(x)
"""
edit:
Amol Bhandekar
I already posted this in my first reply..
In your code, return I cause loop to terminate so can't try to compare other remaining elements...
Hope it clear now..
"""