Reputation: 2138
This code will raise NameError: name 'i' is not defined
:
for n in range(2, 101):
for i in range(2, n):
if n % i == 0:
break
if n % i != 0:
print(n, end=' |')
This code will execute without error:
n = 97
if True:
for i in range(2, n):
if n % i == 0:
break
if n % i != 0:
print(n, end=' |')
Could anybody tell why?
Upvotes: 1
Views: 60
Reputation: 189910
When n
is 2, range(2,n)
will be an empty list, and so the body of that loop will not execute at all.
Upvotes: 4
Reputation: 15872
That has nothing to do with scopes, in fact for
loops in python do not create their own scopes unless it is in a list comprehension
. The reason you are getting an error is i
is not getting created in the first code.
for n in range(2,101):
# at first iteration n == 2
for i in range(2,n):
# this is equivalent to range(2,2) in first iteration
So, there is nothing to iterate on, hence no value is assigned to i
. And when it goes to n % i
, it throws NameError
.
In the second block:
for i in range(2, n):
# value if i is 2
As i
has a value, hence defined, it does not throw NameError
.
Upvotes: 3