Python If / Else indenting


#1

Hi!

I’m brand new to python and programming and I’m a bit confused about indenting if/else statements. When should the if/else statements be in alignment, and when should the indenting not match (like the example below)? In this example, why does the else statement have to be a couple spaces before the above if statement? Thank you so much!!

<def is_prime(x):>
  <if x < 2:>
    <return False>
  <elif x >= 2:>
    <for n in range(2, x-1):>
      <if x % n == 0:>
        <return False>
    <else:>
      <return True>

#2

please format your code:

How do I format code in my posts?

when having an indent question.


#3

If you make an edit, there are no notifications for me. You lucky i saw it :wink:

why are there so many <> in your code?

To understand this problem, you first need to understand that by default, a function returns None at the end. If we want to return something different at the end of the function, we can use the return keyword. But given return is the last thing a function does, when a return keyword is reached, the function ends

thus, if you where to do if/else, the function would end in the first iteration of the loop, meaning the is_prime program fails to run properly

which is why we use for/else, else can only run in this case, when for loop condition becomes false, which can only happen when return False isn’t reached


#4

Thank you so much!!!


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.