简体   繁体   中英

In Python, write a script that determines whether or not a user-inputted number is a prime number

Write a script that determines whether or not a user-inputted number is a prime number and prints "The number that you inputted is a prime number" or "The number that you inputted is not a prime number" depending on what your script finds.

I have code that is failing some of the test cases and I'm not sure why. I see some answers on here that involve calculate the sqrt, but I don't understand why that'd be beneficial.

num= int(input())

if num == 0 or num ==1:
    print('The number you inputted is not a prime number.')
while num < 0:
    break
if num > 0:
    for i in range(2,num):
        if num%i==0:
            print('The number you inputted is not a prime number.')
            break
        else:
            print('The number you inputted is a prime number.')
            break

The code is always right when I try it with a few test cases, but it isn't passing my homework assignment.

Your logic is wrong; you should break only if the condition evaluates to True , since you need to test all numbers up to num ** 0.5 ( num in your code). 9 is an example of a non-prime number that your code evaluates as prime.

You want something like this:

prime = True
if num > 0:
    for i in range(2,num):
        if num % i == 0:
            prime = False
            break

    if prime:
        print(f'{num} is a prime number.')

    else:
        print(f'{num} is not a prime number.')

By setting prime to True at the start and changing it to False only if a factor is found, we can tell, after evaluation of the condition for all the values of i , if the number is prime.

The problem occurs in the logic below:

for i in range(2,num):
    if num%i==0:
        print('The number you inputted is not a prime number.')
        break
    else:
        print('The number you inputted is a prime number.')
        break

To see where the issue occurs, try using your code to check if 9 is prime. Your for loop does the following:

  1. i = 2
  2. if num % i == 0 , not prime, break.
  3. else , prime, break.

This means that your for loop is guaranteed to stop at i==2 . In other words, your definition for a prime number, according to this algorithm is 'any odd number'.

To fix this, you need to find a way to allow the loop to iterate between all the remaining possible divisors, without breaking after the first iteration.

I'm going to stop there, to give you a chance to see if you can figure the rest out yourself. If you can't make any progress, let me know, and I'll give another hint.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM