Factors of a number in Python

Factors are numbers which divide the number evenly.
Factors of 12 are 1, 2, 3, 4, 6, 12
Factors ( of a number ) are numbers which when divide the number they leave 0 as reminder
  • Video Tutorial on Factors of a number


Here is the code to get factors of any number.
n=25 # change this value 
for i in range (1,n+1):
  if(n%i==0):
    print(i,end=', ')
Output
1, 5, 25,
Modulus is the reminder of a division. Here n%i returns 0 if reminder of division is zero. For all the numbers where reminder is 0 we are printing by using if condition checking.

Using user input

All inputs are string data type by default. We can use int() to change this to integer.
n=int(input("Enter a number : "))
#n=25
for i in range (1,n+1):
  if(n%i==0):
    print(i,end=', ')

Using less looping

In above code we are looping from 1 till the input number. We can observe that the factors are always less than or equal to half of the number. So there is no need to use the loop till the number, we can stop looping after checking half of the input number. We will again use int() to convert any float value to integer.
The number ( n ) is the factor of itself so we may print this number at the end to complete the list.
n=125
for i in range (1,int(n/2)+1):
  if(n%i==0):
    print(i,end=', ')
print(n)    
Output
1, 5, 25, 125
All Sample codes
Fibonacci series Prime Numbers Armstrong Number


plus2net.com



Post your comments , suggestion , error , requirements etc here





Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer