I'm trying to figure out how to print the final line of code for this - whether it's a prime number or not. I can't seem to get it to print with the code I have. Any help would be appreciated. Thanks!!
number = int(input("Enter a positive number to test: "))
while number <= 0:
print ("Sorry, only positive numbers. Try again.")
number = int(input("Enter a positive number to test: "))
test = 2
number1 = number - 1
for x in range (0, number1):
trial = number % test
if trial != 0:
print (test, "is NOT a divisor of", number, "...")
break
print (number, "is a prime number!")
else:
print (test, "is a divisor of", number, "...")
break
print (number, "is not a prime number!")
test = test + 1
The break
statement ends the execution of the branch. The following print
statement is never reached.
To get the correct functionaility use a boolean value and perform the check at the end:
is_prime = True
for x in range (2, number):
trial = number % x
if trial != 0:
print (x, "is NOT a divisor of", number, "...")
else:
is_prime = False
print (x, "is a divisor of", number, "...")
if is_prime:
print (number, "is a prime number!")
else:
print (number, "is not a prime number!")
You also do not need to use a variable test
. Use the x
from your range directly.
Have a look at the Python reference for the keyword for more information.
Syntax:
if expression:
statement(s)
else:
statement(s)
It executes all statements with break so print will be never happen...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.