Click here to Skip to main content
15,921,295 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Python
<pre>num = int(input('enter number:'))
if num <= 2:
    if num == 2:
        print(('Yes, it is a prime number')
    else : 
        print('No, it is not a prime number')
else :
    for i in range(2,num) :    
        if (num % i) == 0:
            print('No, it is not a prime number')
            break
        else :
            print('Yes, it is a prime number')   
            break 


What I have tried:

Python
<pre>num = int(input('enter number:'))
if num <= 2:
    if num == 2:
        print(('Yes, it is a prime number')
    else : 
        print('No, it is not a prime number')
else :
    for i in range(2,num) :    
        if (num % i) == 0:
            print('No, it is not a prime number')
            break
        else :
            print('Yes, it is a prime number')   
            break 
Posted
Updated 10-Dec-20 9:19am
Comments
CHill60 10-Dec-20 12:14pm    
What is the error reported?
Richard Deeming 10-Dec-20 12:16pm    
What error, and on what line?

NB: You have a logic error in your code. For example, if you enter 4, which is not a prime number, you will print out:
* No, it is not a prime number
* Yes, it is a prime number

For larger numbers, the problem will be worse.

Step through your code in a debugger, and it should be obvious why that's happening.

You have an unclosed bracket on line 5
Python
print(('Yes, it is a prime number')
That should either be
Python
print('Yes, it is a prime number')
or
Python
print(('Yes, it is a prime number'))
 
Share this answer
 
In addition to Solution 1.
Chabge your code to:
Python
num = int(input('enter number:'))
if num <= 2:
    if num == 2:
        print('Yes, it is a prime number')
    else : 
        print('No, it is not a prime number')
else :
    for i in range(2,num) :    
        print(i) # to print each divisor tested
        if (num % i) == 0:
            print('No, it is not a prime number')
            break
        else :
            print('Yes, it is a prime number')   
            break 

you should get a surprise. Input 9, just to see.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900