To create a program in Python divisible that checks whether a number is divisible by another number, you must understand how to use lists in Python. along with that, the source code will also include the lambda or anonymous function.
Divisibility is a mathematical concept in which it is checked whether a number is perfectly divisible by another number. The divisibility of a number is proven true when the remainder obtained after the division of two numbers is zero.
The lambda function in Python is a single-line function. It is declared without any name, thus known as an anonymous function. It can have any number of arguments but includes only one expression. Unlike a normal function that is defined in Python, the lambda function does not need to be defined with a unique name.
Source Code
The Python divisible program that tests whether a number is divisible by another number, that is, gives the result zero when the modulus or remainder (%) operator is applied is provided below.
list_1 = [13, 14, 87, 44, 70, 09]
result = list (filter (lambda x: (x % 7 == 0), list_1))
print (“Numbers that are divisible by 7 are:”, result)
Output:
The number that are divisible by 7 are [14, 70]
This way, the user can change the list of numbers that are to be tested. Along with that, the number whose divisibility needs to be tested can be changed as well. This way, you can test the divisibility of several numbers using a few lines of code. You can also ask the user to enter the numbers that need to be checked for divisibility.
Alternative Method:
If you do not want to use the lambda function, then you can execute the program that is provided below. It shows how one can check the divisibility using only the modulus or remainder operator and if…else condition.
num = int (input (“Enter the number whose divisibility needs to be checked:”))
div = int (input (“Enter the number with which divisibility needs to be checked:”))
if num%div == 0:
print (“The number is divisible.”)
else:
print (“The number is not divisible.”)
You can also insert a condition that checks whether the div is greater than num. If so, then the divisibility test cannot be checked.
Questions
What is divisible in Python?
Python divisible is the program that checks whether a number is divisible by another number using the “%” operator.
How do you check if a number is divisible in Python?
To check if a number is divisible in Python, you will have to check if the remainder obtained after the division is zero. If yes, then the number is divisible.
How do you check if a number is divisible by 3 in Python?
To check if a number is divisible by 3 in Python, use the remainder operator. If the number, let’s say, num%3 == 0, then the number will be divisible.
How do you check divisibility by 5 in Python?
In Python, the remainder operator (“%”) is used to check the divisibility of a number with 5. If the number%5 == 0, then it will be divisible.
Leave a Reply