Python Program to Find Numbers Divisible by Another Number

Posted in

Python Program to Find Numbers Divisible by Another Number
vinaykhatri

Vinay Khatri
Last updated on April 18, 2024

    In this article, we will provide Python source code that can find the numbers divisible by another number, specifically, from a list of numbers.

    Prerequisite Topics to Create the Program

    • Python Input/Output .
    • Python Lambda functions.
    • Filter function in Python.
    • Python operators.
    • Python split operator.

    Steps to Create the Program

    1. First, we ask the user to enter the values in a list separated by space.
    2. Next, we ask the user to enter a number n , which is supposed to be another number that divides the numbers present in the list.
    3. Then using the filter and lambda functions, we will find out all the numbers present in the list that are divisible by another number n .
    4. At last, we will display all the numbers present in the list that are divisible by the number n .

    Note:

    • filter(function, iterable): filter() is an inbuilt function in Python. It accepts 2 values as arguments, function, and iterable (list, tuple, dictionary, et cetera). It passes the iterable values one by one to the function and returns a filter object that contains all the values of the list that satisfy the condition of the function.
    • lambda arguments: return expression: Lambda functions are also known as Anonymous functions and they are used to write user-defined functions.

    Python Program to Find Numbers Divisible by Another Number

    Python Code:

    num_list = list (map(int, input("Enter the numbers separated by spaces: ").split()))
    n= int(input("Enter the divisible number: "))
    result = list(filter(lambda x:x%n==0 , num_list))
    print("The numbers divisible by",n, "are",result)

    Output 1:

    Enter the numbers separated by spaces: 12 23 32 34 36 46 55 75 78 71
    Enter the divisible number: 3
    The numbers divisible by 3 are [12, 36, 75, 78]

    Output 2:

    Enter the numbers separated by spaces: 12 23 32 34 36 46 55 75 78 71
    Enter the divisible number: 4
    The numbers divisible by 4 are [12, 32, 36]

    Conclusion

    By now, you should know how to write a Python program to find all the numbers from a list that are divisible by a number n . To thoroughly implement the Python code, one needs to have a good understanding of anonymous functions and the filter function.

    People are also reading:

    Leave a Comment on this Post

    0 Comments