To find the factors of a number in Python, check which positive integers divide it with no remainder. For example, the factors of 12 are 1, 2, 3, 4, 6, 12. The % operator checks the remainder: n % i == 0 means i is a factor of n.
Start with this original for-loop example for 25.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubn=25 # change this value
for i in range (1,n+1):
if(n%i==0):
print(i,end=', ')
Output:
1, 5, 25,
For 25, the factors are 1, 5 and 25. The trailing comma comes from print(i, end=', '); a later example shows how to format the output without it.
A factor (or divisor) is a whole number that divides another whole number exactly. For positive integers, both 1 and the number itself are factors. We focus on positive factors here; for negative integers, the same positive factors apply to the absolute value.
n = 12
for i in range(1, n + 1):
if n % i == 0:
print(i, end=" ")
Output:
1 2 3 4 6 12
Here the condition is true for 1, 2, 3, 4, 6 and 12. For a detailed explanation of the Python if statement, follow the related tutorial.
The loop checks 1 through n. The range(1, n + 1) expression includes n because the end of a Python range is excluded. When n % i is zero, i divides n evenly.
| Expression | Meaning | For n = 12 |
|---|---|---|
range(1, n + 1) | Test each positive integer up to n | 1 through 12 |
n % i | Remainder after n is divided by i | 12 % 5 is 2 |
n % i == 0 | True when i is a factor | 12 % 4 == 0 |
print(i) | Display a matching factor | 1, 2, 3, 4, 6, 12 |
n = 12
for i in (3, 5, 6):
print(f"{n} % {i} = {n % i}; factor: {n % i == 0}")
Output:
12 % 3 = 0; factor: True
12 % 5 = 2; factor: False
12 % 6 = 0; factor: True
The original interactive example calls int() to convert the text returned by input() into an integer. Change the number at the prompt when you run this in a terminal or Colab.
n=int(input("Enter a number : "))
#n=25
for i in range (1,n+1):
if(n%i==0):
print(i,end=', ')
Output:
Enter a number : 1, 2, 3, 4, 6, 8, 12, 24,
The sample run supplies 24 at the prompt. int() raises ValueError for text such as hello. See the Python data types tutorial.
Instead of printing inside the loop, collect the divisors and use join() to produce a clean comma-separated result. The list comprehension uses the same factor test as the first example.
n = 25
factors = [i for i in range(1, n + 1) if n % i == 0]
print(", ".join(str(i) for i in factors))
Output:
1, 5, 25
You can also retain the Python list, for example [1, 5, 25], if you want to count or reuse the factors.
The original tutorial reduces the search to half of n and then prints n itself. For every integer n > 1, every positive proper factor is at most n // 2. The number itself is added separately.
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
This preserves the original 125 demonstration. For positive integers, n // 2 is preferable to int(n / 2) because it avoids floating-point conversion.
n = 125
factors = [i for i in range(1, n // 2 + 1) if n % i == 0]
factors.append(n)
print(factors)
Output:
[1, 5, 25, 125]
This returns the same four factors without mixing numbers and display punctuation. The full-range method is often simpler to learn; the next method is substantially faster for large integers.
If i divides n, then n // i is its paired factor. Checking only through math.isqrt(n) therefore finds both factors while making far fewer checks. This standard-library function gives the exact integer square root without floating-point rounding. Python 3.8 or newer is required for math.isqrt().
from math import isqrt
n = 36
factors = set()
for i in range(1, isqrt(n) + 1):
if n % i == 0:
factors.add(i)
factors.add(n // i)
print(sorted(factors))
Output:
[1, 2, 3, 4, 6, 9, 12, 18, 36]
For the perfect square 36, 6 is paired with itself. The set prevents it from appearing twice; sorted() returns the factors in ascending order.
For repeated tasks, put the square-root approach into a function. This implementation returns a sorted list of positive factors and rejects zero, which does not have a finite set of positive divisors.
from math import isqrt
def positive_factors(n):
if n == 0:
raise ValueError("Zero has infinitely many positive divisors")
n = abs(n)
found = set()
for i in range(1, isqrt(n) + 1):
if n % i == 0:
found.add(i)
found.add(n // i)
return sorted(found)
print(positive_factors(28))
print(positive_factors(125))
Output:
[1, 2, 4, 7, 14, 28]
[1, 5, 25, 125]
Use positive_factors(12), positive_factors(125) or another nonzero integer. The function returns data, so it can be used for prime checks and calculations.
1 has one positive factor: itself. A negative integer has the same positive factors as its absolute value, plus the negative versions of those factors if signed factors are needed. Zero is divisible by every nonzero integer, so it cannot be represented by a finite list of all factors.
from math import isqrt
def positive_factors(n):
if n == 0:
raise ValueError("Zero has infinitely many positive divisors")
n = abs(n)
result = set()
for i in range(1, isqrt(n) + 1):
if n % i == 0:
result.update((i, n // i))
return sorted(result)
print("1:", positive_factors(1))
print("-12:", positive_factors(-12))
try:
print(positive_factors(0))
except ValueError as error:
print("0:", error)
Output:
1: [1]
-12: [1, 2, 3, 4, 6, 12]
0: Zero has infinitely many positive divisors
The pairs (1, 36), (2, 18), (3, 12), (4, 9) and (6, 6) explain why the square-root approach works. Printing both halves makes the relationship visible.
from math import isqrt
n = 36
for i in range(1, isqrt(n) + 1):
if n % i == 0:
print(i, "x", n // i, "=", n)
Output:
1 x 36 = 36
2 x 18 = 36
3 x 12 = 36
4 x 9 = 36
6 x 6 = 36
Once the factors are stored in a list, len() counts them and sum() adds them. This helps with number-property exercises such as perfect numbers.
n = 28
factors = [i for i in range(1, n + 1) if n % i == 0]
print("Factors:", factors)
print("Count:", len(factors))
print("Sum of proper factors:", sum(factors[:-1]))
print("Perfect number:", sum(factors[:-1]) == n)
Output:
Factors: [1, 2, 4, 7, 14, 28]
Count: 6
Sum of proper factors: 28
Perfect number: True
A positive integer greater than one is prime if its only positive factors are 1 and itself. The related Python prime numbers tutorial covers additional prime-number methods.
for n in (1, 2, 9, 13, 29):
factors = [i for i in range(1, n + 1) if n % i == 0]
is_prime = n > 1 and len(factors) == 2
print(n, "prime:", is_prime)
Output:
1 prime: False
2 prime: True
9 prime: False
13 prime: True
29 prime: True
For a large positive n, the basic search makes n checks, the half-range search about n/2 checks, and the square-root approach approximately √n checks. The difference grows quickly for larger values.
from math import isqrt
for n in (25, 125, 10000, 1000000):
print(f"n={n}: full={n}, half={n // 2}, sqrt={isqrt(n)}")
Output:
n=25: full=25, half=12, sqrt=5
n=125: full=125, half=62, sqrt=11
n=10000: full=10000, half=5000, sqrt=100
n=1000000: full=1000000, half=500000, sqrt=1000
An input prompt accepts text. Convert with int() inside try/except, reject zero, and use abs() for negative integers. Avoid silently converting decimal strings such as 3.8 to 3; factors are discussed here for integers.
from math import isqrt
def positive_factors(n):
if n == 0:
raise ValueError("Enter a nonzero integer")
n = abs(n)
factors = set()
for i in range(1, isqrt(n) + 1):
if n % i == 0:
factors.update((i, n // i))
return sorted(factors)
for text in ("24", "-10", "0", "hello", "3.8"):
try:
number = int(text)
print(text, "->", positive_factors(number))
except ValueError as error:
print(text, "->", error)
Output:
24 -> [1, 2, 3, 4, 6, 8, 12, 24]
-10 -> [1, 2, 5, 10]
0 -> Enter a nonzero integer
hello -> invalid literal for int() with base 10: 'hello'
3.8 -> invalid literal for int() with base 10: '3.8'
This video accompanies the original Plus2Net explanation of factors and remainder-based loops. The code examples above can be run independently of the video.
range(1, n + 1) is empty when n < 1; use abs(n) if you need positive factors.int(input(...)) raises ValueError for text and decimal strings; validate the input first.end=", " prints a separator after the last factor; collect values and use join().0 as having a finite divisor list.int(n / 2) with n // 2 and use math.isqrt(n) for integer square roots.range() endpoint is skipped: write range(1, n + 1) when testing through n.The Google Colab notebook includes executable challenges with assertions. Before opening the solutions, try:
48 without a trailing comma.97. Is the number prime?144, ensuring 12 appears only once.18 and 24 and identify the common factors.360 using math.isqrt().1, -36, and 0 with meaningful results.Loop through candidate integers and keep the values where n % i == 0. For large numbers, use math.isqrt(n) and record each matching divisor together with n // i.
The positive factors are 1, 2, 3, 4, 6, 12. Each divides 12 with remainder zero.
Yes. Check candidates up to the integer square root and collect both numbers in each factor pair. This generally makes far fewer checks than testing every integer from 1 through n.
1 has one positive factor: 1. Every positive integer divides zero, so zero has infinitely many positive factors and needs special handling in a factor-listing program.
Yes, when you explicitly decide what you want to return. To find positive factors of a negative integer, take its absolute value with abs(n).
The factors of 12 are 1, 2, 3, 4, 6, 12, while its distinct prime factors are 2 and 3. See the prime numbers examples.
No. The exercises use built-in Python features and the standard-library math module. For math.isqrt(), use Python 3.8 or newer.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.