Else without if inside loop?

In the code snippet below, else is appearing outside the for loop and if condition is inside the for loop. My understanding is that ‘else’ cannot exist without ‘if’. However, in this case the ‘if’ condition is inside a for loop and ‘else’ is outside which means the scope of ‘if’ is only limited to the loop and it should not be available outside. Could you please clarify? Please note that ‘if’ and ‘else’ are at different indentation. The code can be found under “break and continue” keyword topic under “learn-python-3-from-scratch” course.

n = 10
x = 4
found = False # This bool will become true once x in found

for i in range(0, n):
if x == i+1:
found = True
print(“Number found”)
print(“Number not found”)

Type your question above this line.


Answering my own question since I found the answer on stackoverflow. It appears that unlike most other programming languages, there is no “loop” or “block” level scoping in python. This means things like variables defined inside the loop are accessible outside the loop. Similarly, “if” inside a for loop is visible outside the loop and you can simply add “else” corresponding to that “if”.

Hi @Milind

Python does not have blocks, as do some other languages (C/C++ or Java). It is a design choice in Python, which often makes some tasks more manageable than in other languages with the typical block scope behavior. But sometimes, you would still miss the standard block scopes because you might have large temporary arrays, which should be free as soon as possible.