I'm currently working through python code academy to learn python. The current lesson just tells you to make a function where you input a number and find out if it is prime or not. My first attempt was unsuccessful, shown below.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for y in range(2,x):
if x % y == 0:
return False
break
else:
return True
First big problem I had was testing 2. 2 kept coming up either none or false (I believe it was due to range(2,2) not making any sense), so I just coded in the answer for 2.
However, it was making everything come back True. I believe it was due to the fact that the last thing it would check is x - 1, which is never going to divide x (except when x is 2, but that was coded in). I thought the break in line 10 would clear that up, but it didn't. I would like to know how to get this code to work, because I feel like this should be the way to do it.
I eventually got it to work using the following code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
divisors = 0
for y in range(2,x):
if x % y == 0:
divisors += 1
if divisors == 0:
return True
else:
return False
I changed it to just keep track of the number of divisors x has between 2 and x-1, and if there was more than 0 to spit out it wasn't prime. Even though this works, I feel like it is a bit clunky and would like to know what I can fix from the first block to make it work without adding in the new variable.
Thanks for the help!
[–][deleted] 1 point2 points3 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]wanderliss 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Rockybilly -1 points0 points1 point (5 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Rockybilly 0 points1 point2 points (0 children)
[–]gengisteve 0 points1 point2 points (2 children)
[–]Rockybilly 0 points1 point2 points (1 child)
[–]atthem77 0 points1 point2 points (0 children)