def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(2))
for the argument 2, the program returns true. but in for loop the if condition is satisfied because 2%2==0. Instead of returning false why it returns true. please help me to understand.
I’m not sure that I fully understand your question, but if I do: print(is_prime(2)) will always return True, because range(2, int(num**0.5) + 1) where num == 2 produces range(2, 2), which means the loop is never run.
To add: the first number that will have the for: loop execute more that once, is 9, because range(2, int(9**0.5) + 1) produces range(2, 4): start at 2 and stop at 3
int(2 ** 0.5) + 1 == 2, and range(2, 2) is an empty range (it’s a “half-open” range, meaning that the start value is included but the end value is not).
I try to avoid multiple return points in a function, as it tends to be harder to de-bug; better to fully evaluate the operation and have a single return point, so that you can better follow the logic.
That advice is mostly irrelevant in general, and certainly wouldn’t have helped here. Early return is WAY clearer than setting a flag, breaking out of all necessary loops and other constructs, and finally reaching the sole blessed return statement at the end.
Nearly every modern programming language allows a return from any point within a function. Don’t shy people away from it.
The moment you say it in a thread like this, though, it’s not just “what I tend to do”, it’s advice to someone who doesn’t know much about programming. Suboptimal advice is a dangerous trap.