I have to determine if all the numbers in a list are prime numbers and then return a boolean "True" or "False" statement depending on the outcome. I made some conditional statements inside of a for loop to see if the number was prime or not.
Here's the code:
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
break
elif (i % 2 == 0) and (i % i == 1):
is_prime = False
return is_prime
break
else:
is_prime = True
return is_prime
The problem is, and I saw this in the Python Visualizer, the for loop stops iterating after checking the first value in the list. I don't understand why as the syntax is the same as for loops I've used in the past.
I plugged in some example values like: all_primes([5,2,11,37])
or all_primes([5,2,4,37])
and the return value is always true since 5 is the first number on the list and the only number that is being iterated.
Any ideas as to why?
You should see the problem the other way around.
If you you find a number which is not prime you should return False, and after your loop end you should return True.
You have a
return
and abreak
in yourif/else
block, you should get rid of them. Also thereturn
in theelse
should be outside, or it will just return whenever he finds a "prime".After this, you should know, that you are not really checking primes. Here is not the most efficient way but its clear how to:
EDIT: without the
map
functions, you just have to iterate with afor
loop: