For loop only iterates once within function
Question:
I would appreciate some help or an explanation. The code currently returns 1. I would like the below code to return 3 simply counting the numbers divisible by 10 within my list. It seems the for loop only iterates once. How can I get this code to iterate again? Thank you. Code Below.
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))
Answers:
This will work. The return keyword in wrong place. Therefore it will return/stop before loop through the all element in the list.
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))
you are returning the counter variable after one loop. Once you return the function gonna stop.
second thing the code also needs to be indented properly
you can implement it correctly by returning the counter when the loop ends like this:
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))
I would appreciate some help or an explanation. The code currently returns 1. I would like the below code to return 3 simply counting the numbers divisible by 10 within my list. It seems the for loop only iterates once. How can I get this code to iterate again? Thank you. Code Below.
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))
This will work. The return keyword in wrong place. Therefore it will return/stop before loop through the all element in the list.
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))
you are returning the counter variable after one loop. Once you return the function gonna stop.
second thing the code also needs to be indented properly
you can implement it correctly by returning the counter when the loop ends like this:
def divisible_by_ten(num):
counter = 0
for i in num:
if i % 10 == 0:
counter += 1
return counter
print(divisible_by_ten([20, 25, 30, 35, 40]))