By default, a function returns None at the end of the function. If we want to return something else at the end of the function, we can use the return keyword.
Given return is the last thing a function does, when a return keyword is reached, the function ends
so when using if/else, the loop ends in the first iteration, which is desired behavior to see if x is a prime number.
using for/else, else only runs when when loop condition becomes false, this can’t happen when the loop breaks/returns. This approach make sense, given x is only a prime number when it gets through the loop successfully.
The whole point of my reply was explaining precisely that? Your reply doesn’t even indicate you understood anything i attempted to explain.
11 is a prime number, because 11 is not divisible by 2, 3, 4, …, 10
9 isn’t a prime number, because 9 is divisible by 3.
However, if you use if/else:
for n in range(2, x):
if x % n == 0:
// function call
you can see that the loop only makes one iteration (because of the print statement i inserted). the if condition test 9 % 2 == 0, which is false, so the else clause runs (given you use if/else), which returns True, which will cause the function to end, as i explained, a function ends when a return keyword is reached
the indent determines when return True is reached, which has massive impact on the way your program works, if your program works correctly (for/else) or faulty (if/else)
Oh my god thank you so much! So can i just confirm, when using the if/else, the reason why the result was True was because the moment it hit the first part of the range, 9 % 2 == 0 which is False, it immediately moves on to the else statement, hence returning True. In other words, for the statement to end on the “if” of the if/else, every part of the range must return True.
However for the for/else, the moment it returns false on the loop, the else statement doesn’t run, because the loop condition for the ‘for’ is false?