'How can I solve the below Python question [closed]

Evenly Divisible:

Create a function that gets three arguments x,y,z as input and return the number of values in the range between x and y(both x and y are included) and evenly divisible by z.

Sample case:- Sample Input 1 20 2 Sample Output 10

Explanation:

From the limit 1 to 20 the values 2,4,6,810,1214,16,18,20 are evenly divisible by 2,so the total number is evenly divisible by 10.



Solution 1:[1]

If you understand it, you might use list comprehension as well.

def evendiv(x,y,z):
    return(len([i for i in range(x, y+1) if i%z==0]))

print(evendiv(2,26,4))

Solution 2:[2]

I don't understand what your question is trying to say, but here is a function to find all numbers between x and y that are divisible by z.

def divisible_in_range(x, y, z):
    if x > y:
        x, y = y, x
    for i in range(x, y + 1):
        if i % z == 0:
            print(i)

# Call it with 3 values

This prints all the numbers, like so (inputs 1, 20, 10)

2
4
6
8
10
12
14
16
18
20

If this isn't what you expected, include more detail about what your function should do in the question.

I would recommend trying out some code before posting a question, as all this code requires is knowing what a function is and knowing the syntax for a for loop.

EDIT Looking at your comment, you could do this:

def divisible_in_range(x, y, z):
    if x > y:
        x, y = y, x
    count = 0
    for i in range(x, y + 1):
        if i % z == 0:
            print(i)
            count += 1
    return count

And call it like this:

print(f"The number of numbers between 1 and 20 divisible by 2 is: {divisible_in_range(1, 20, 2)}")

Output:

2
4
6
8
10
12
14
16
18
20
The number of numbers between 1 and 20 divisible by 2 is: 10

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anand Gautam
Solution 2