For-Else and Try-Except-Else in Python

Reading Time: 2 minutes

If you’re familiar with any programming language, you’d know that an else statement is generally used after an if or else-if (elif in Python) statement. But, why the hell there’s a structure called for-else and try-except-else in Python? Let’s find out.

What is “Else”?

I think I have to make an introduction for those who don’t know what else statement is. else works when none of the if statements work. Let’s give an example for it:

a = 10

if a == 9:
  print("A")
elif a == 8:
  print("B")
else:
  print("C")

As you can see “a” is equal to number 10. The first if statement checks whether a is 9 or not. It’s clearly a false statement so we move to the second statement which checks if “a” is equal to 8. This is also false so we’re out of statements and else statement will be triggered and it’ll print “C” to the screen.

if elif else in Python

For-Else in Python

We’ve learned what else statement is, but how is it applied to the for-loop?

Assume that you have a for-loop. If you iterate every single element without a break, the else will trigger. Check this piece of code:

for i in range(5):
  print(i)
else:
  print("Finished")

The output will be: 1 2 3 4 Finished. Because there was no break inside of the for-loop. If we modify the code like the example below, it wouldn’t run the else statement:

for i in range(5):
  print(i)
  if (i == 4):
    break
else:
  print("Finished")

The output will be: 1 2 3 4 this time.

Try-Except-Else in Python

Unlike the for-else example, this time else will work when there are no exceptions in the code. For instance:

try:
	print("Hi")
except:
	print("Error")
else:
	print("No Error at all!")

The output will be:

Hi
No Error at all!

Because there were no exceptions (or errors in other words) in the try block. If we trigger an error inside the try block, the except block would work and the else statement wouldn’t work.

Conclusion

If you wanna watch my 1-minute long video about this topic, here you go!

Leave a Comment