Write A Python Script To Generate Divisors Of A Number

In the below article lets users enter an integer number and generate all the  divisors of a given integer number.

Divisors of a number are the factors of a number,  it may  range from 1 to number. 

 

Write A Python Script To Generate Divisors Of A Number

 

 


Write A Python Script To Generate Divisors Of A Number


Let's take a variable named as number and ask the user to enter the number using the input function call and then convert it into an integer type.  Use print() function call to print user friendly messages.

number = int(input("Enter a Number : "))
print(f"Divisors of a Number : {number} are ...")




Use the for loop to iterate from 1 to the number and get the range as index.  use if statement and try dividing the number by the index using the modulus operator.  if the remainder is 0  you have found devices of a number, then print the number using print function call.

for index in range(1, number + 1):
   if number % index == 0:
       print(index)




Complete Python program
========================


number = int(input("Enter a Number : "))
print(f"Divisors of a Number : {number} are ...")

for index in range(1, number + 1):
   if number % index == 0:
       print(index)



Output
=============
Enter a Number : 25
Divisors of a Number : 25 are ...
1
5
25




Output
===============
Enter a Number : 99
Divisors of a Number : 99 are ...
1
3
9
11
33
99





Write A Python Script To Generate Divisors Of A Number Using list comprehension method.

The for loop and if statement can be combined into a single list comprehension method as shown below.

Python Program
=======================

number = int(input("Enter a Number : "))
print(f"Divisors of a Number : {number} are ...")

divisors = [index for index in range(1, number + 1) if number % index == 0]
print(divisors)




Output
================
>python main.py
Enter a Number : 21
Divisors of a Number : 21 are ...
[1, 3, 7, 21]



Conclusion
======================
Execute the above Python program by providing a random integer number and find the divisors of the given number,  note down the results.

Comment down below if you have any suggestions to improve the above Python program

Post a Comment

0 Comments