Try walking through your program step by step for a simple input, like 4:
for x in range(2, 4): # The range contains [2, 3].
if 4 % x == 0: # First loop x == 2; 4 % 2 == 0, so this block runs.
print(x) # 2 is printed.
elif 4 % x != 0: # Second loop == 3; 4 % 3 == 1 != 0, so this block runs.
print(f"{4} is a prime number") # 4 is a prime number is printed.
You could use a flag to keep track of whether any divisors were found:
is_prime = True
for x in range(2, n):
if n % x == 0:
is_prime = False
print(x)
if is_prime:
print(f"{n} is prime")
A few other thoughts:
You could speed up the program by only checking for divisors up to sqrt(n)
Your current implementation only prints multiple divisors once, and also prints non-prime divisors. Is that intentional? (e.g. 8 == 2*2*2 prints 2 once, then 4)
n = int(input("enter number "))
m = []
for x in range(2,n):
if n % x == 0:
m.append(x)
if m:
for x in m:
print(x)
elif not m:
print(f"{n} is prime number")
This works as well. I recently started python and I’m new to programming language.