Click here to Skip to main content
15,040,212 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just started to learn for loops yesterday, and I'm already having trouble. The function should find all numbers between num1 and num2 inclusive that is divisible by both 5 and 7.
Here's what I got.

(for some reason my indents are wrong on this site)

What I have tried:

Python
def fivesAndSevens(num1, num2):
    for fivesAndSevens in range(num1, num2):
        if fivesAndSevens % 5 == 0 and fivesAndSevens % 7 == 0:
            print(fivesAndSevens(num1, num2))
        else:
            print("none")

fivesAndSevens(10, 90)
Posted
Updated 2-Feb-21 11:53am
v3

try, it should be better
Python
def fivesAndSevens(num1, num2):
    for fivesAndSevens in range(num1, num2):
        if fivesAndSevens % 5 == 0 and fivesAndSevens % 7 == 0:
            print(fivesAndSevens(num1, num2))
        else:
            print("none")

fivesAndSevens(10, 90)
   
Comments
OriginalGriff 2-Feb-21 17:55pm
   
Um ... Are you sure? :laugh:
Patrice T 2-Feb-21 18:04pm
   
Just removed the recursion. :)
OriginalGriff 3-Feb-21 1:53am
   
And the output of "none" fifty times within the loop? :D
Patrice T 3-Feb-21 2:06am
   
It is let to OP as an exercise.
My change only removes the infinite recursion, which is already a nice improvement.
You can't print the "none" result inside the loop - and that's the only way the else can match with the if.

So create a variable before the loop, and set it to False.
Inside the loop, when you find a value that is divisible by both 5 and 7 print it, and set the variable to True
After the loop, check the variable. If it's still False then you found no such values so you need to print your "none found" message.

Give it a try: it's not difficult code to write!
   
Working with generator..
Python
def fnc(num_1,num_2):
    max=num_1
    min=num_2
    
    if(num_1<num_2):
        max=num_2
        min=num_1
        
    for i in range(min,max+1):
        if (i%5==0 and i%7==0):
            yield i
        

for z in fnc(1,100):
    print(z)
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900