Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop only iterates once within function

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]))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading