here is my code:
def is_prime(x):
if x < 2:
return False
else:
for i in range(2,x):
if x % i == 0:
return False
else:
return True
print is_prime(508)
I don't understand why the last else: return true works with the indentation. If I type
else:
for i in range(2,x):
if x % i == 0:
return False
else:
return True
Then def is_prime(2) returns none? why?
Because in python, a for-loop can have an else-clause.
This clause is executed if the loop exits normally. If the loop is exited by using the break statement, the else is not entered.
I suggest you read up the official doc and if it's still unclear, this blog summarizes the concept fairly well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With