I have this assignment where I have to write a code to determine if a number is a prime number or not and I couldn't come up with a solution so I searched the net and found the following code( the first one) and then I wrote the exact same code but with a different name and it didn't work for numbers like 65, 75, ... and said they are prime numbers, while they aren't. Can you help me find out what I'm doin wrong! thank you in advance!
The code I copied:
num=int(input())
if num > 1:
for i in range(2, int(num/2) 1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
my code:
addad=int(input())
if addad>1:
for i in range(2,int(addad/2) 1):
if (addad%i)==0:
print("not prime")
break
else:
print("prime")
break
else:
print("prime")
CodePudding user response:
They are not same.
In the above code you use for...else
but in the second you used if...else
. Take a closer look at the indentations. White space has great significance in python.
I think you might need to read a little about for/else in python. You will find the difference for sure.
little description, else
in the same indent with for
will run if the for
loop goes to the end(no breaks). so in the first snippet else
will run at the end of the for
with condition of no breaks happening, while in the code that you write else
is IN the for
block and will run in each cycle and it is bind to the if
command above.
CodePudding user response:
here's one way to do it, note that 1 is not a prime number:
def check_prime(x):
if x >= 2:
for y in range(2,x):
if not (x % y):
return 'not prime'
else:
return 'not prime'
return 'prime'
check_prime(int(input('Enter number to check: ')))
Output:
Enter number to check: 31
'prime'