Is there a limit to the number of elif statements allowed?


In Python, is there a limit to the number of elif statements that are allowed?


No, there is no strict limit to how many elif statements you can include after an if statement. You can add as many as you need into the program, not taking into account memory or other possible limitations like hardware.

The only strict limit is that there can only be one if and one else per if/elif/else statement block, but there is no limit on the number of elif.



Why can’t I use an else statement? It causes an error. However, when I used the elif, it worked.

Please post a link to the exercise where this problem is occurring. We can only speculate until we see your complete code submission, so please also post that in your reply.

1 Like

Hello Sir,
I am having a doubt regarding the elif statement. Can you kindly bother to look at it and help me please!

def greater(x):
    if x > 5:
      return "the number is greater than 5"
    elif x > 7 :
      return "the number is greater than 7"
    elif x > 9 :
      return "the number is greater than 9"


when I am running this code, its not working and I am not able to recognize the mistake.

Remember that if-elif statements are evaluated in order and only if the preceding statement’s boolean condition was False. This means the if statement is evaluated first, then elif x > 7 if x > 5 == False, then elif x > 9 if x > 7 == False.

Let’s take your function call of greater(11). The if statement is evaluated first. Since 11 > 5 == True, the code inside the if block is executed. Now, the if-elif block is exited, meaning that both elif statements are not even evaluated. What changes could you make to return the desired output? There are several ways to accomplish this.


Thank you so much for the answer. Now I understood how it happens .
Also Can I just take the biggest number above so as to get the desired output for example in place of “5” maybe write “9” or is there some other way to solve this?

The order matters, so generally speaking if greater is the criterion, then start with the largest, and work your way down.


There are many ways to solve this. I encourage you to play around with the code and try it out for yourself! Yes, putting if x > 9, then elif x > 7, then elif x > 5 would work since you are working from the largest number to the smallest number.

1 Like

Oh ohkay , thank you so much.

1 Like

Oh yes i did exactly that and it worked fine… Now I know what to do… Thank you so much…