-3

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]))
Joseph
  • 1
  • 2

2 Answers2

1

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]))
hassan
  • 26
  • 6
  • Just for fun (and to show the power of Python) a one-liner solution: `return sum(1 for i in num if not i % 10)` – Matthias Sep 15 '22 at 06:11
0

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]))
YJR
  • 1,099
  • 3
  • 13