user6572652 - 1 year ago 47

Python Question

I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), so that it appears only after the "else" function in the "for" loop and not the "if div == 0:" statements? Thank you!

`while True:`

num = int(input("Enter a positive number to see if it's a prime number: "))

if num > 1:

break

elif num == 1:

print("1 is technically not a prime number.")

else:

print("Number cannot be negative- try again.")

for num1 in range(2,num):

div = num%num1

if div == 0:

print(num1,"is a divisor of",num,"... stopping.")

print(num,"is not a prime number.")

break

else:

print(num1,"is NOT a divisor of",num,"... continuing")

print(num,"is a prime number!")

Answer Source

Given that you have already covered a division by 1, all you have to do is count if there is only one more divisor (the number itself). So to keep your code structure I added a counter.

```
while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
count = 0
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
count += 1
print(num1,"is NOT a divisor of",num,"... continuing")
if count == 1:
print(num,"is a prime number!")
```