I'm doing an online course on Python 2.7 and one thing on if-else statements threw me off a bit:
def is_prime(num):
for n in range(2,num):
if num%n == 0:
print "Not prime"
break
else:
print "Number is prime"
I know what the function does, but what is confusing me here is why Python understands and accepts the syntax of the if-else part (it wasn't explained in the video I was watching either). I would've expected the else
to be at the same level of the if
statement. Of course this would mean you'd get "Number is prime" a bunch of times for everything except 3, so it's great that this works as it is, but I'm looking for some sort of rule when I can do this. I tried googling it, but I haven't found this case on the normal tutorial sites.