FAQ: Learn Python - Practice Makes Perfect - factorial FAQ: Learn Python - Practice Makes Perfect - is_prime

faq
#23

If x is a number, it is not iterable. Consider, do we need nested loops to solve this problem?

#24

So I tried the following code to also print out whether x is a prime or not, instead of just none and False. Why does it print only

#25

So I tried the following code to also print out whether x is a prime or not, instead of just none and False. Why does it print only 4 is not a prime and not 2 is a prime?

def is_prime (x):
  if x < 2:
    return False
  else:
    for n in range (2, x-1):
      if x % n == 0:
        print x, "is not a prime"
        return False
      else:
        print x, "is a prime"
        return True
        
print is_prime (2)
print is_prime (4)
#26

return means handing back a value to the function call, and indicating that the function is done/completed.

your function returns in the first iteration of the loop, so the return will break free from the loop (so to speak)

#27

def is_prime (x):
if x < 2:
return False
else:
for n in range (2, x-1):
if x % n == 0:
print x, “is not a prime”
else:
print x, “is a prime”

is_prime (2)
is_prime (4)

But even like this it does not print 2 is a prime. And I am not returning True or False in between. I don’t understand how I can have it print 2 is a prime as well.

#28

for x = 2 the loop will never run, there are no steps to take.

you solve two problems at once figuring out that a number is prime number after the loop ran all its iteration without the if condition being true, thus you get for else

#29

Somewhere in the documentation it says that when,

for...
else...

is used, there should be a break in the for loop. No break, no else.

#30

In a for - else loop, break causes else to be bypassed, so if you are searching for something and do not find it, you can print or return an appropriate notification. (The else clause also executes if the for loop is bypassed.):

for n in [3,7,9,10]:     # break is encountered
    if n % 2 == 0:
        print("{} is even".format(n))
        break
else:
    print("no even numbers")
# Output:
10 is even

vs

for n in [3,7,9]:     # break is not encountered
    if n % 2 == 0:
        print("{} is even".format(n))
        break
else:
    print("no even numbers")
# Output:
no even numbers

vs

for n in []:     # No break, but for loop never entered
    if n % 2 == 0:
        print("{} is even".format(n))        
else:
    print("no even numbers")

# Output:
no even numbers

Of course, if break is omitted, it won’t work like you want:

for n in [3,7,9, 10]:       # No break here
    if n % 2 == 0:
        print("{} is even".format(n))        
else:
    print("no even numbers")

# Output:
10 is even
no even numbers
1 Like