Reputation: 41
My goal is to create a program that checks whether a number is a prime number and displays the total number of factors if it is not a prime number.
I have started the code but I realize I need to store my factors in a list in order for the number of factors to be displayed. Here is my (edited) Python code so far:
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum+1):
if(userNum % x == 0):
factor = 0
numFactors.append(x)
factor = factor + 1
print(userNum,"is not a prime number")
print("Number of factors: ", factor)
break
else:
print(userNum,"is a prime number")
Can someone please tell me how to continue with storing factors into my list (numFactors)? Thank You!
Upvotes: 1
Views: 150
Reputation: 1513
Your mistake is lacking check whether x is equal to userNum, that is in the end of the loop.
My other suggestion is you remove variable factor
as this can be known from the length of the numFactors list.
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum + 1):
if userNum % x == 0:
numFactors.append(x)
if userNum == x:
print("Factors: " + str(numFactors))
if len(numFactors) == 2:
print(userNum, "is a prime number")
else:
print(userNum, "is not a prime number")
print("Number of factors: ", len(numFactors))
Upvotes: 0
Reputation: 864
You need to use append()
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum+1):
if(userNum % x == 0):
factor = 0
numFactors.append(x)
factor = factor + 1
...
...
But there is a logical flaw in your code. Try input as 99.
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
# A prime number (or prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Hence range starting from 2
for x in range(2, userNum+1):
if(userNum % x == 0):
numFactors.append(x)
if len(numFactors) == 1:
print(userNum, " is a prime number")
else:
print(userNum,"is not a prime number")
print("Number of factors: ", len(numFactors))
print("Factors : ", numFactors)
Enter a number: 99
User Number: 99
99 is not a prime number
Number of factors: 5
Factors : [3, 9, 11, 33, 99]
Upvotes: 1
Reputation: 6740
First, you need to put the line that defines numFactors
, numFactors = []
, outside of and before the for
loop. Otherwise, it will be continually set to an empty list for each iteration of the loop.
Values can be added to the end of a list by using the list's append
method. For example, numFactors.append(2)
would add 2
to the end of the list.
Upvotes: 0